package com.xixun.launcher;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import gnph.util.Arrs;
import gnph.util.IOs;
import gnph.util.JSList;
import gnph.util.JSMap;

public class ProgEditActi extends FragmentActivity implements View.OnFocusChangeListener {

    LinearLayout _pageList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prog_edit);
        _pageList = findViewById(R.id.pageList);

        var name = getIntent().getStringExtra("name");
        if(name==null) {
            var names = new File(Util.programsDir).list();
            int i=1;
            while(Arrs.indexOf(names, name = "新建节目"+i) > -1) i++;
        }
        var lbTitle = (TextView) findViewById(R.id.lbTitle);
        lbTitle.setText(name);

        var btnClose = (Button) findViewById(R.id.btnClose);
        btnClose.setOnClickListener((View v)->finish());

        var btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener((View v)->{
            var pages = new JSList<JSMap>();
            var cnt = _pageList.getChildCount();
            var progDir = new File(Util.programsDir+"/"+lbTitle.getText());
            progDir.mkdirs();
            for(int i=0; i<cnt; i++) {
                var item = (PageItem) _pageList.getChildAt(i);
                var src = new File(item.path);
                if(! src.isFile()) continue;
                var filename = ""+i+" - "+src.length();
                try {
                    IOs.writeClose(new FileOutputStream(new File(progDir, filename)), new FileInputStream(src));
                    pages.add(new JSMap("file", filename));
                } catch (Exception e) {
                    Util.printStackTrace(e);
                }
            }
            try {
                new JSMap("pages", pages).writeClose(new FileOutputStream(new File(progDir, "cfg.json")));
            } catch (Exception e) {
                Util.printStackTrace(e);
                Util.makeText(this, "cfg.json write error: "+e).show();
            }
            finish();
        });

        add(0);
    }

    PageItem _item;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==111) {
            var path = data.getData().getPath().replace("/document/primary:","/storage/emulated/0/");
            System.out.println(path+" "+new File(path).exists());
            _item.removeViewAt(0);
            _item.path = path;
            _item.lbImg = new ImageView(this);
            _item.lbImg.setOnFocusChangeListener(this);
            boolean unset = true;
            if(path.endsWith(".mp4")) {
                var retriever = new MediaMetadataRetriever();
                try {
                    retriever.setDataSource(path);
                    var img = retriever.getFrameAtTime(1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                    _item.lbImg.setImageBitmap(_item.img = img);
                    unset = false;
                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        retriever.release();
                    } catch (IOException ignored) {
                    }
                }
            }
            if(unset) _item.lbImg.setImageURI(_item.uri = data.getData());
            var prm = new LinearLayout.LayoutParams(480, 270);
            _item.addView(_item.lbImg, 0, prm);
            onFocusChange(_item.lbImg, true);
        }
    }

    void add(int idx) {
        var pageItem = new PageItem(this);
        var lbImg = new Button(this);
        lbImg.setText("添加文件");
        pageItem.addView(lbImg, new LinearLayout.LayoutParams(480, 270));
        lbImg.setOnClickListener((View v)->{
            var inte = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            inte.setType("*/*");
            startActivityForResult(inte, 111);
            _item = (PageItem) v.getParent();
        });

        var hhh = new LinearLayout(this);

        pageItem.lbIdx = new TextView(this);
        pageItem.lbIdx.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        hhh.addView(pageItem.lbIdx, new LinearLayout.LayoutParams(120, 84));

        var btn = new Button(this);
        btn.setText("✚");
        btn.setOnFocusChangeListener(this);
        btn.setOnClickListener((View v)->{
            var item = (LinearLayout) v.getParent().getParent();
            var ppp = (LinearLayout) item.getParent();
            var iii = ppp.indexOfChild(item);
            add(iii+1);
        });
        hhh.addView(btn, new LinearLayout.LayoutParams(84, 84));

        btn = new Button(this);
        btn.setText("↑");
        hhh.addView(btn, new LinearLayout.LayoutParams(84, 84));
        btn.setOnFocusChangeListener(this);
        btn.setOnClickListener((View v)->{
            var item = (LinearLayout) v.getParent().getParent();
            var list = (LinearLayout) item.getParent();
            var iii = list.indexOfChild(item);
            list.removeViewAt(iii);
            list.addView(item, iii-1);
            v.requestFocus();
            var cnt = list.getChildCount();
            for(int i=0; i<cnt; i++) {
                var pitem = (PageItem) list.getChildAt(i);
                pitem.lbIdx.setText(""+(i+1));
            }
        });

        btn = new Button(this);
        btn.setText("↓");
        hhh.addView(btn, new LinearLayout.LayoutParams(84, 84));
        btn.setOnFocusChangeListener(this);
        btn.setOnClickListener((View v)->{
            var item = (LinearLayout) v.getParent().getParent();
            var list = (LinearLayout) item.getParent();
            var iii = list.indexOfChild(item);
            list.removeViewAt(iii);
            list.addView(item, iii+1);
            v.requestFocus();
            var cnt = list.getChildCount();
            for(int i=0; i<cnt; i++) {
                var pitem = (PageItem) list.getChildAt(i);
                pitem.lbIdx.setText(""+(i+1));
            }
        });

        btn = new Button(this);
        btn.setText("\uD83E\uDEA3");
        hhh.addView(btn, new LinearLayout.LayoutParams(84, 84));
        btn.setOnClickListener((View v)->{
            var item = (LinearLayout) v.getParent().getParent();
            var list = (LinearLayout) item.getParent();
            list.removeView(item);
            var cnt = list.getChildCount();
            for(int i=0; i<cnt; i++) {
                var pitem = (PageItem) list.getChildAt(i);
                pitem.lbIdx.setText(""+(i+1));
            }
        });

        pageItem.addView(hhh);

        _pageList.addView(pageItem, idx);

        var cnt = _pageList.getChildCount();
        for(int i=0; i<cnt; i++) {
            var item = (PageItem) _pageList.getChildAt(i);
            item.lbIdx.setText(""+(i+1));
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(! hasFocus) return;
        var pare = v.getParent();
        if(! (pare instanceof PageItem)) {
            pare = pare.getParent();
            if(! (pare instanceof PageItem)) return;
        }
        var item = (PageItem) pare;
        var bigImg = (ImageView) findViewById(R.id.bigImg);
        if(item.img!=null) bigImg.setImageBitmap(item.img);
        else if(item.uri!=null) bigImg.setImageURI(item.uri);
    }

    static class PageItem extends LinearLayout {
        ImageView lbImg;
        Bitmap img;
        Uri uri;
        String path;
        TextView lbIdx;
        public PageItem(Context context) {
            super(context);
            setOrientation(LinearLayout.VERTICAL);
        }
    }
}
