package com.yutou.jianr_mg.views;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.leon.lfilepickerlibrary.LFilePicker;
import com.umeng.analytics.MobclickAgent;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.MGamePackname;
import com.yutou.jianr_mg.Data.TModfilePath;
import com.yutou.jianr_mg.Interfaces.ModInterface;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.ModUtils;
import com.yutou.jianr_mg.Tools.RootUtils;
import com.yutou.jianr_mg.Tools.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class UserDefinedActivity extends AppCompatActivity implements View.OnClickListener {
    private Button srcFile;
    private Spinner outPath;
    private Spinner packageName;
    private Button execute;
    private TextView logcat;
    private Handler handler;
    private List<String> pName;
    private List<File> files;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_defined);
        handler = new Handler();
        files = new ArrayList<>();
        pName = new ArrayList<>();
        initView();

    }


    private void initView() {
        srcFile = findViewById(R.id.srcFile);
        outPath = findViewById(R.id.outPath);
        packageName = findViewById(R.id.packageName);
        execute = findViewById(R.id.execute);
        logcat = findViewById(R.id.logcat);

        srcFile.setOnClickListener(this);
        execute.setOnClickListener(this);

        Utils.initGamePackName();
        Utils.initInstallPath();

        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                if (AppData.packnames == null || AppData.packnames.size() == 0) {
                    Utils.initGamePackName();
                } else if (AppData.installPath == null || AppData.installPath.size() == 0) {
                    Utils.initGamePackName();
                } else {
                    handler.post(() -> {
                        List<String> title, out;
                        title = new ArrayList<>();
                        out = new ArrayList<>();
                        for (MGamePackname packname : AppData.packnames) {
                            pName.add(packname.getPackname());
                            title.add(packname.getZhname());
                        }
                        for (TModfilePath modfilePath : AppData.installPath) {
                            out.add(modfilePath.getPath());
                        }
                        outPath.setAdapter(new ArrayAdapter<>(UserDefinedActivity.this, android.R.layout.simple_spinner_dropdown_item, out));
                        packageName.setAdapter(new ArrayAdapter<>(UserDefinedActivity.this, android.R.layout.simple_spinner_dropdown_item, title));
                        cancel();
                    });
                }
            }
        }, 0, 100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.srcFile:
                new LFilePicker()
                        .withActivity(this)
                        .withRequestCode(100)
                        .withStartPath(Application.application.getFilesDir()+"/jianRMG")//指定初始显示路径
                        .withIsGreater(false)//过滤文件大小 小于指定大小的文件
                        .withMutilyMode(true)
                        .withFileSize(5*1024*1024)//指定文件大小为500K
                        .start();
                break;
            case R.id.execute:
                if(!AppData.packnames.get(packageName.getSelectedItemPosition()).getZhname().contains("[ROOT]")){
                    ModUtils modUtils=ModUtils.init(UserDefinedActivity.this);
                    for (File file : files) {
                       modUtils.notRootInstall(file, outPath.getSelectedItem().toString());
                    }
                    modUtils.notRootInstallStart(new ModInterface() {
                        @Override
                        public void onAction(boolean flag, int type) {
                            if(flag){
                                handler.post(()->logcat.append("\n复制成功"));
                            }else{
                                handler.post(()->logcat.append("\n复制失败"));
                            }
                        }
                    },false);
                    return;
                }
                boolean flag = false, flag2 = false;
                if (files.size() == 0) {
                    logcat.append("\n未选择任何文件");
                    return;
                }
                for (File file : files) {
                    logcat.append("\n执行复制：" + file.getAbsolutePath() + " 到" + outPath.getSelectedItem().toString());
                    flag = RootUtils.init(this).exec("cp -r -f " + file.getAbsolutePath() + " /data/data/" + pName.get(packageName.getSelectedItemPosition()) + outPath.getSelectedItem().toString());
                    flag2 = RootUtils.init(this).exec("chmod 777" + " /data/data/" + pName.get(packageName.getSelectedItemPosition()) + outPath.getSelectedItem().toString() + file.getName());
                    RootUtils.init(this).exec("chmod +x" + " /data/data/" + pName.get(packageName.getSelectedItemPosition()) + outPath.getSelectedItem().toString() + file.getName());
                    if(!flag){
                        logcat.append("\n复制失败："+file.getAbsolutePath());
                    }
                }
                if (flag && flag2) {
                    logcat.append("\n操作成功");
                } else {
                    logcat.append("\n操作失败");
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                //如果是文件选择模式，需要获取选择的所有文件的路径集合
                files.clear();
                List<String> list = data.getStringArrayListExtra("paths");
                Toast.makeText(getApplicationContext(), "选中了" + list.size() + "个文件", Toast.LENGTH_SHORT).show();
                logcat.append("\n已选择 " + list.size() + "个文件");
                for (String s : list) {
                    logcat.append("\n" + s);
                    files.add(new File(s));
                }
            }
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
}
