package com.qy.utils;

import com.qy.Interfaces.SmaliApkToolsPath;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.applet.Main;

import java.io.*;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class AutoPackageSDK {
    private AutoRandomAdSDK randomAdSDK;
    private String version;
    private String packageName;
    File gdtsdk, uniplaysdk, qysdk;

    public AutoPackageSDK(SmaliApkToolsPath inter, String version, String packageName) {
        this.version = version;
        this.packageName = packageName;
        File gdtPath = new File("input" + File.separator + "gdtSDK" + File.separator);
        File unplayPath = new File("input" + File.separator + "uniplaySDK" + File.separator);
        File qysdkPath = new File("input" + File.separator + "qySDK" + File.separator);
        if (!gdtPath.exists() || Objects.requireNonNull(gdtPath.listFiles()).length == 0) {
            inter.smaliPath("广点通SDK不存在，请放置到input" + File.separator + "gdtSDK文件夹中");
            return;
        }
        gdtsdk = Objects.requireNonNull(gdtPath.listFiles())[0];
        if (!unplayPath.exists() || Objects.requireNonNull(unplayPath.listFiles()).length == 0) {
            inter.smaliPath("聚量SDK不存在，请放置到input" + File.separator + "gdtSDK文件夹中");
            return;
        }
        uniplaysdk = Objects.requireNonNull(unplayPath.listFiles())[0];
        if (!qysdkPath.exists() || Objects.requireNonNull(qysdkPath.listFiles()).length == 0) {
            inter.smaliPath("趣赢SDK不存在，请放置到input" + File.separator + "gdtSDK文件夹中");
            return;
        }
        qysdk = Objects.requireNonNull(qysdkPath.listFiles())[0];

        JSONArray array = new JSONArray();

        JSONObject gdt = new JSONObject();
        gdt.put("file", gdtsdk.getAbsolutePath());
        gdt.put("version", version);
        gdt.put("type", "1");
        gdt.put("index", 0);
        gdt.put("packageName", packageName + ".tgd");
        array.put(gdt);

        JSONObject unplay = new JSONObject();
        unplay.put("file", uniplaysdk.getAbsolutePath());
        unplay.put("version", version);
        unplay.put("type", "5");
        unplay.put("index", 1);
        unplay.put("packageName", packageName + ".up");
        array.put(unplay);

        JSONObject qy = new JSONObject();
        qy.put("file", qysdk.getAbsolutePath());
        qy.put("version", version);
        qy.put("type", "0");
        qy.put("packageName", packageName + ".ww");
        qy.put("index", 3);
        array.put(qy);

        File sdk = new File("packageSDK");

        Tools.deleteFiles(sdk.getAbsolutePath());
        if (!sdk.exists()) {
            sdk.mkdirs();
        }


        outAssetsQY(0, "0");
        outAssetsQY(1, "4");
        outRes();
        new AutoRandomAdSDK(array, new SmaliApkToolsPath() {
            @Override
            public void smaliPath(String path) {
                System.out.println("打包完成:" + path);
               delete(gdtPath,gdtsdk);
               delete(unplayPath,uniplaysdk);
               delete(qysdkPath,qysdk);
                outAssetsADS(path);
                copy();
                zip();
                System.out.println("制作SDK完成");
            }
            private void delete(File path,File sdk){
                for (File file : path.listFiles()) {
                    if(!file.getName().equals(sdk.getName())){
                        file.delete();
                    }
                }
            }
        });


    }

    private void outAssetsQY(int index, String type) {
        JSONObject json = Tools.loadConfig(new File("config.cfg"));

        json.put("switch", index + 1 + "");
        String path = json.getString("out");
        String name = json.getJSONArray("array").getString(Integer.parseInt(json.getString("switch")) - 1) + ".jar";
        File file = new File(path + name);
        if (file.exists())
            file.delete();

        JarToAJar.start(json);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (file.exists()) {
                    File input = new File(json.getString("out")
                            + json.getJSONArray("array").getString(index) + ".jar");
                    Tools.toAJar(json.getString("dx"), input.getAbsolutePath(), input.getAbsolutePath().replace(input.getName(), "dexTmp.jar"));
                    File outFile = new EncryptJar().encrypt(new File(input.getAbsolutePath().replace(input.getName(), "dexTmp.jar")), json.getString("out")
                                    + json.getJSONArray("array").getString(index), Integer.parseInt(type)
                            , Integer.parseInt(version));
                    System.out.println(outFile.getAbsolutePath());
                    File assets = new File("packageSDK" + File.separator + "assets");
                    Tools.copyFile(outFile.getAbsolutePath(), assets.getAbsolutePath(), true);
                    outFile.delete();
                    input.delete();
                    timer.cancel();
                }
            }
        }, 0, 100);


    }

    private void outAssetsADS(String path) {
        JSONArray array = new JSONArray(path);
        File assets = new File("packageSDK" + File.separator + "assets");
        File libs = new File("packageSDK" + File.separator);
        assets.mkdirs();
        libs.mkdirs();
        for (int i = 0; i < array.length(); i++) {
            JSONObject item = array.getJSONObject(i);
            System.out.println(">>" + item.toString());
            if (item.getString("type").equals("0")) {
                Tools.copyFileToName(item.getString("path"), libs.getAbsolutePath(), "classes.jar", true);
            } else {
                Tools.copyFile(item.getString("path"), assets.getAbsolutePath(), true);
            }
            File file = new File(item.getString("path"));
            file.delete();
        }

    }

    private void outRes() {
        //new File("packageSDK" + File.separator + "jni").mkdirs();
        File xmlFolder = new File("packageSDK" + File.separator + "res" + File.separator + "xml");
        xmlFolder.mkdirs();
        File manifest = new File("packageSDK" + File.separator + "AndroidManifest.xml");
        File srcManifest = new File("input" + File.separator + "Documents" + File.separator + "AndroidManifest.xml");
        Tools.copyFile("input" + File.separator + "Documents" + File.separator + "file_paths_5.xml",
                xmlFolder.getAbsolutePath(), true);
        Tools.copyFile("input" + File.separator + "Documents" + File.separator + "network_security_config.xml",
                xmlFolder.getAbsolutePath(), true);
        try {
            BufferedReader reader = new BufferedReader(new FileReader(srcManifest));
            String tmp;
            StringBuilder str = new StringBuilder();
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp.replace("{packagename}", packageName)).append("\n");
            }
            reader.close();
            FileWriter writer = new FileWriter(manifest);
            writer.write(str.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void zip(File file) throws Exception {
        String cd = "cd " + new File("packageSDK").getAbsolutePath();
        File sdk = new File("packageSDK" + File.separator + "sdk.aar");
        File files=new File("packageSDK");
        String aapt=new File("aapt.exe").exists()?new File("aapt.exe").getAbsolutePath():"aapt";
        for (File listFile : file.listFiles()) {
            if(listFile.isDirectory()){
                zip(listFile);
            }else if(!listFile.getName().equals("sdk.aar")){
                String path=listFile.getAbsolutePath().replace(files.getAbsolutePath(),"");
                String exec=aapt+" r "+sdk.getAbsolutePath()+" "+path.substring(1)+"\n";
                Runtime.getRuntime().exec("cmd /c "+cd+" && "+exec);
                Thread.sleep(100);
                exec =aapt+ " a " + sdk.getAbsolutePath() + " " + path.substring(1) + "\n";
                Runtime.getRuntime().exec("cmd /c "+cd+" && "+exec);
                Thread.sleep(100);
            }

        }
    }
    private void zip() {
        try {
            Tools.copyFile(new File("input" + File.separator + "Documents" + File.separator + "sdk.aar").getAbsolutePath(),
                    new File("packageSDK").getAbsolutePath(), true);
            String cd = "cd " + new File("packageSDK").getAbsolutePath() + "\n\r";
            Process process=Runtime.getRuntime().exec(new String[]{"cmd"});
            OutputStream stream =process.getOutputStream();
            stream.write(cd.getBytes());
            stream.flush();
            stream.close();
            process.destroy();
            zip(new File("packageSDK"));
            File copy=new File("packageSDK"+File.separator+"copy");
            if(copy.exists()){
                zip(copy);
            }
            stream.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void copy(){
        try{
            File copyPath=new File("input"+File.separator+"Documents"+File.separator+"copy");
            if(copyPath.exists()){
             Tools.copyFile(copyPath.getAbsolutePath(),new File("packageSDK").getAbsolutePath(),true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        int a=1;
        new AutoPackageSDK(new SmaliApkToolsPath() {
            @Override
            public void smaliPath(String path) {
            //com.tanggttaxc.langtt.mi
            }
        }, "5700", a==0?"com.luckyboy.mmxing":"com.prujwk.jdyphn");
    }
}
