package com.yutou.jianr_mg.Tools;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import me.drakeet.materialdialog.MaterialDialog;

/**
 * Created by 58381 on 2018/2/6.
 */

public class RootUtils {
    private Context context;
    private static RootUtils rootUtils;
    private Runtime localProcess;
    private Process process;
    private DataOutputStream stream;
    private int exitValue;

    public static RootUtils init(Context context) {
        if (rootUtils == null) {
            rootUtils = new RootUtils(context);
            rootUtils.init();
            rootUtils.println("chmod 7777 /data/data/com.yutou.jianr_mg/files/busybox");
        }
        return rootUtils;
    }

    public static void setRootInstallModel(Context context) {
        RadioButton rawRoot, busyBox;
        RadioGroup group;
        rawRoot = new RadioButton(context);
        busyBox = new RadioButton(context);
        group = new RadioGroup(context);
        rawRoot.setText("安卓自带指令");
        busyBox.setText("busyBox(有问题，在完善)");
        group.addView(rawRoot);
        group.addView(busyBox);
        if (RootUtils.init(context).isBusyBox()) {
            group.check(busyBox.getId());
        } else {
            group.check(rawRoot.getId());
        }
        busyBox.setEnabled(false);
        MaterialDialog dialog = new MaterialDialog(context);
        dialog.setTitle("设置ROOT安装模式");
        dialog.setContentView(group);
        dialog.setPositiveButton("确定", view -> {
            SharedPreferences preferences=context.getSharedPreferences("config",Context.MODE_PRIVATE);
            if(busyBox.isChecked()){
                preferences.edit().putInt("rootInstallModel",0).apply();
            }else{
                preferences.edit().putInt("rootInstallModel",1).apply();
            }
            dialog.dismiss();
            Utils.toast(context,"设置完成");
        });
        dialog.show();
    }

    private void init() {
        try {

            localProcess = Runtime.getRuntime();
            process = localProcess.exec("ls"+"\n");
            stream = new DataOutputStream(process.getOutputStream());
            if(su()){
                boolean tmp=isBusyBox();
                isBusyBox=false;
                println("chmod 777" + Application.application.getFilesDir() + "/files/busybox");
                println("chmod +x" + Application.application.getFilesDir() + "/files/busybox");
                isBusyBox=tmp;
            }
            System.out.println("尝试获取ROOT权限");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private RootUtils(Context context) {
        this.context = context;
    }

    private static int isRoot = -1;

    public static boolean su() {
        if (isRoot != -1) {
            return isRoot == 1;
        }
        try {
            Process localProcess = Runtime.getRuntime().exec("su\n");
            BufferedReader reader = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
            Object localObject = localProcess.getOutputStream();
            DataOutputStream localDataOutputStream = new DataOutputStream(
                    (OutputStream) localObject);
            localDataOutputStream.writeBytes("ls -l /data/data\n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            boolean result = false;
            int resultCode=-1;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                result = localProcess.waitFor(500, TimeUnit.MILLISECONDS);
            }else{
                System.out.println("b");
                resultCode=localProcess.waitFor();
            }
            localDataOutputStream.close();
            reader.close();
            localProcess.exitValue();
            if (result||resultCode == 0 || resultCode == 128) {
                isRoot = 1;
                return true;
            } else {
                isRoot = -1;
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isRoot = -1;
        return false;
    }

    public boolean exec(String exec) {
        try {
            if (!isBusyBox()) {
                return println(exec);
            }
            String newExec = "./data/data/" + context.getPackageName() + "/files/busybox " + exec;
            Log.i("ROOT", newExec);
            stream.writeBytes(newExec + "\n");
            stream.flush();
        } catch (Exception e) {
            try {
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            init();
            Utils.toast(context,"busyBox失效，转为系统指令尝试");
            isBusyBox=false;
            return println(exec);
        }
        return true;
    }
    private boolean isBusyBox=false;
    public boolean println(String exec) {
        try {
            if (isBusyBox) {
                return exec(exec);
            }
            String[] execs=new String[]{
                    "su",
                    "-c",
                    exec
            };
            // exec="./data/data/"+context.getPackageName()+"/files/busybox-armv6l "+exec;
            Log.i("SystemROOT", exec);
            Process process = localProcess.exec(execs);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = "", tmp;
            List<String> list = new ArrayList<>();
            while ((tmp = reader.readLine()) != null) {
                //str+=tmp;
                list.add(tmp);
            }
            reader.close();
            for (String string : list) {
                Log.i("ROOT get", string);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean isBusyBox() {
        SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        switch (preferences.getInt("rootInstallModel", 0)) {
            case 0:
                return false;
            case 1:
                return false;
            default:
                return false;
        }
    }
}
