package com.qy.ui;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.security.Permission;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;

import com.sun.javaws.exceptions.ExitException;
import org.json.JSONArray;
import org.json.JSONObject;

import com.qy.Interfaces.SmaliApkToolsPath;
import com.qy.utils.EncryptJar;
import com.qy.utils.JarToAJar;
import com.qy.utils.JarToBase;
import com.qy.utils.Tools;

public class AppMain extends JFrame {
    private JList<String> configList;
    private JButton zipToJar, jarToBase, reload, btnAdbPull;
    private JTextField log;
    public static JSONObject json;
    private Vector<String> vector;
    public static boolean isOpenWindows = false;
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextField txtCom;
    private JButton btnUserBase;
    private JTextField textPackName;
    private JButton btnRestartapp;
    private JLabel lblactivity;
    private JTextField textActivity;
    private JMenuBar menuBar;
    private JTextField uFilePath;
    private JSeparator separator;
    private JMenuItem menuItem_1;
    private JCheckBox openWindows;
    private JMenu mnBasetools;
    private JMenuItem mntmbase;
    private JMenuItem mntmBase;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        new AppMain();
    }

    public AppMain() {

        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        json = Tools.loadConfig(new File("config.cfg"));
        initView();
        initData();
        log.setText("已载入配置文件");

        separator = new JSeparator();
        separator.setBounds(247, 149, 158, 2);
        getContentPane().add(separator);

        repaint();
    }

    private void initData() {
        JSONArray array = json.getJSONArray("array");
        vector = new Vector<>();
        for (int i = 0; i < array.length(); i++) {
            vector.add(array.getString(i));
        }
        configList.setListData(vector);
    }


    private void initView() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        setTitle("\u8F6C\u6362\u5668v2.8");
        // TODO Auto-generated constructor stub
        setSize(900, 456);
        getContentPane().setLayout(null);

        configList = new JList<String>();
        configList.setBounds(0, 0, 1, 1);

        JScrollPane scrollBar = new JScrollPane(configList);
        scrollBar.setBounds(51, 49, 147, 215);
        getContentPane().add(scrollBar);

        zipToJar = new JButton("\u8F6Cjar");
        zipToJar.addMouseListener(new MouseAdapter() {
            File file;
            Timer timer;
            String name, path;

            @Override
            public void mouseClicked(MouseEvent e) {
                if (configList.getSelectedIndex() < 0) {
                    new TextToDalog("警告", "列表未选择");
                    return;
                }
                json.put("switch", configList.getSelectedIndex() + 1 + "");
                path = json.getString("out");
                name = json.getJSONArray("array").getString(Integer.parseInt(json.getString("switch")) - 1) + ".jar";
                file = new File(path + name);
                if (file.exists())
                    file.delete();

                JarToAJar.start(json);

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

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (file.exists()) {
                            log.setText("已生成" + name);
                            timer.cancel();
                        } else {
                            log.setText("正在生成");
                        }
                    }
                }, 0, 100);

            }
        });
        zipToJar.setBounds(247, 72, 158, 27);
        getContentPane().add(zipToJar);

        jarToBase = new JButton("\u52A0\u5BC6Jar");

        jarToBase.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (configList.getSelectedIndex() < 0) {
                    new TextToDalog("警告", "列表未选择");
                    return;
                }
                json.put("switch", configList.getSelectedIndex() + 1 + "");
                new EditToDalog("需要版本号", "请输入资源版本号", "", new SmaliApkToolsPath() {
                    String version;

                    @Override
                    public void smaliPath(String path) {
                        // TODO Auto-generated method stub
                        version = path;
                        if (version == null) {
                            return;
                        }
                        new EditToDalog("资源类型", "请输入资源类型\n0=内核\n4=自主广告\n1=广点通\n5=聚量\n11=万维\n13=穿山甲", "", new SmaliApkToolsPath() {
                            @Override
                            public void smaliPath(String path) {
                                // TODO Auto-generated method stub
                                File input = new File(json.getString("out")
                                        + json.getJSONArray("array").getString(Integer.parseInt(json.getString("switch"))  -1) + ".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(Integer.parseInt(json.getString("switch")) - 1) + "_encrypt.jar", Integer.parseInt(path)
                                        , Integer.parseInt(version));
                                log.setText("data路径为:" + outFile.getAbsolutePath());
                            }
                        });
                    }
                });
                /*
                 * JarToBase.start(json.getString("out") +
                 * json.getJSONArray("array").getString(Integer.valueOf(json.getString("switch")
                 * ) - 1) + ".jar", true);
                 */

            }
        });
        jarToBase.setBounds(247, 109, 158, 27);
        getContentPane().add(jarToBase);

        reload = new JButton("\u91CD\u8F7D\u914D\u7F6E\u6587\u4EF6");
        reload.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                initData();
                json = Tools.loadConfig(new File("config.cfg"));
                log.setText("已重置");
            }
        });
        reload.setBounds(51, 13, 153, 27);
        getContentPane().add(reload);

        log = new JTextField("\u521D\u59CB\u5316");
        log.setBorder(new LineBorder(Color.BLACK, 0));
        log.setHorizontalAlignment(SwingConstants.LEFT);
        log.setForeground(Color.BLACK);
        log.setEditable(false);
        log.setBounds(51, 340, 766, 31);
        getContentPane().add(log);

        txtCom = new JTextField();
        txtCom.setHorizontalAlignment(SwingConstants.LEFT);
        txtCom.setText("adb push \"" + new File("").getAbsolutePath() + "/[jar]/data/data/[packname]/plugs/");
        txtCom.setBounds(444, 73, 293, 27);
        getContentPane().add(txtCom);
        txtCom.setColumns(10);

        JLabel lblAdb = new JLabel("adb\u6307\u4EE4");
        lblAdb.setBounds(444, 51, 72, 18);
        getContentPane().add(lblAdb);

        btnAdbPull = new JButton("adb");
        btnAdbPull.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String cmd = txtCom.getText();
                cmd = cmd.replace("[packname]", textPackName.getText());
                cmd = cmd.replace("[jar]", configList.getSelectedValue().toString() + ".jar");
                try {
                    System.out.println(cmd);
                    Runtime.getRuntime().exec("adb root");
                    Runtime.getRuntime().exec("adb remount");
                    Runtime.getRuntime().exec(cmd);
                    log.setText("执行：" + cmd);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    log.setText("执行失败");
                }

            }
        });
        btnAdbPull.setBounds(444, 295, 147, 27);
        getContentPane().add(btnAdbPull);

        new ButtonGroup();

        btnUserBase = new JButton("\u52A0\u5BC6\u6587\u4EF6");
        btnUserBase.addMouseListener(new MouseAdapter() {
            File file;

            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser jFile = new JFileChooser(new File(new File("").getAbsolutePath()));
                jFile.showOpenDialog(null);
                file = jFile.getSelectedFile();
                new EditToDalog("需要版本号", "请输入资源版本号", "", new SmaliApkToolsPath() {
                    String version;

                    @Override
                    public void smaliPath(String path) {
                        // TODO Auto-generated method stub
                        version = path;
                        if (version == null) {
                            return;
                        }
                        new EditToDalog("资源类型", "请输入资源类型\n0=内核\n4=自主广告\n1=广点通\n5=聚量\n11=万维\n13=穿山甲", "", new SmaliApkToolsPath() {
                            @Override
                            public void smaliPath(String path) {
                                // TODO Auto-generated method stub
                                Tools.toAJar(json.getString("dx"), file.getAbsolutePath(), file.getAbsolutePath().replace(file.getName(), "dexTmp.jar"));
                                File fileOut = new EncryptJar().encrypt(new File(file.getAbsolutePath().replace(file.getName(), "dexTmp.jar")), file.getAbsolutePath() + "_encrypt.jar", Integer.valueOf(path)
                                        , Integer.valueOf(version));
                                System.out.println("data路径为:" + fileOut.getAbsolutePath());
                                if (log != null)
                                    log.setText("data路径为:" + fileOut.getAbsolutePath());

                            }
                        });
                    }
                });
                //JarToBase.start(file.getAbsolutePath(), true);
            }
        });
        btnUserBase.setBounds(247, 160, 158, 27);
        getContentPane().add(btnUserBase);

        JButton btnNewButton = new JButton("\u89E3\u5BC6\u6587\u4EF6");
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser jFile = new JFileChooser(new File(new File("").getAbsolutePath()));
                jFile.showOpenDialog(null);
                File file = jFile.getSelectedFile();
                String fileName = file.getAbsolutePath();
                if (fileName.endsWith("_encrypt.jar")) {
                    fileName = fileName.replace("_encrypt.jar", "_decrypt.jar");
                } else {
                    fileName += "_decrypt.jar";
                }
                EncryptJar.FileData data = new EncryptJar().decrypt(file, fileName);
                new TextToDalog("解码提示", data.toString());
                //JarToBase.start(file.getAbsolutePath(), false);
                log.setText("已解码");
            }
        });
        btnNewButton.setBounds(247, 200, 158, 27);
        getContentPane().add(btnNewButton);

        openWindows = new JCheckBox("\u6253\u5F00\u7A97\u53E3");
        openWindows.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                isOpenWindows = openWindows.isSelected();
            }
        });

        openWindows.setBounds(247, 30, 133, 31);
        getContentPane().add(openWindows);

        JLabel label = new JLabel("\u5305\u540D");
        label.setBounds(444, 113, 72, 18);
        getContentPane().add(label);

        textPackName = new JTextField();
        textPackName.setText("com.luckyboy.mmxing");
        textPackName.setBounds(444, 135, 293, 24);
        getContentPane().add(textPackName);
        textPackName.setColumns(10);

        btnRestartapp = new JButton("\u91CD\u542FAPP");
        btnRestartapp.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Runtime.getRuntime().exec("adb shell am force-stop " + textPackName.getText());
                    Runtime.getRuntime()
                            .exec("adb shell am start " + textPackName.getText() + File.separator + textActivity.getText());
                    log.setText("重启完毕");
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    log.setText("重启失败");
                }
            }
        });
        btnRestartapp.setBounds(595, 295, 147, 27);
        getContentPane().add(btnRestartapp);

        lblactivity = new JLabel("\u4E3BActivity");
        lblactivity.setBounds(444, 164, 119, 18);
        getContentPane().add(lblactivity);

        textActivity = new JTextField();
        textActivity.setText(".MainActivity");
        textActivity.setBounds(444, 185, 293, 24);
        getContentPane().add(textActivity);
        textActivity.setColumns(10);

        JButton btnJavatoajar = new JButton("Jar\u8F6C\u5B89\u5353Jar");
        btnJavatoajar.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser chooser = new JFileChooser(new File(new File("").getAbsolutePath()));
                chooser.showOpenDialog(null);
                File java = chooser.getSelectedFile();
                Tools.toAJar(json.getString("dx"), java.getAbsolutePath(),
                        new File("").getAbsolutePath() + File.separator + java.getName() + "_jar.jar");
                if (AppMain.isOpenWindows) {
                    try {
                        Desktop.getDesktop().open(new File(new File("").getAbsolutePath()));
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                log.setText("已转为Android可用java");
            }
        });
        btnJavatoajar.setBounds(247, 237, 158, 27);
        getContentPane().add(btnJavatoajar);

        JLabel label_t = new JLabel("\u83B7\u53D6\u81EA\u5B9A\u4E49\u6587\u4EF6\u8DEF\u5F84");
        label_t.setBounds(444, 215, 208, 18);
        getContentPane().add(label_t);

        uFilePath = new JTextField();
        uFilePath.setBounds(444, 238, 293, 24);
        getContentPane().add(uFilePath);
        uFilePath.setColumns(10);

        JButton button = new JButton("\u83B7\u53D6");
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser chooser = new JFileChooser(new File(new File("").getAbsolutePath()));
                chooser.showOpenDialog(null);
                File file = chooser.getSelectedFile();
                uFilePath.setText(file.getAbsolutePath());
                log.setText("获取自定义文件路径完成");

            }
        });
        button.setBounds(755, 235, 113, 27);
        getContentPane().add(button);

        menuBar = new JMenuBar();

        setJMenuBar(menuBar);

        JMenu mnNewMenu = new JMenu("\u83DC\u5355");
        menuBar.add(mnNewMenu);

        JMenuItem menuItem = new JMenuItem("\u91CD\u542F");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
                new AppMain();
            }
        });

        mnNewMenu.add(menuItem);

        JMenu menu = new JMenu("\u5DE5\u5177");
        menuBar.add(menu);

        JMenuItem mntmAes = new JMenuItem("AES\u5DE5\u5177");
        mntmAes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new AESUi();
            }
        });
        menu.add(mntmAes);

        JMenuItem mntmSmali = new JMenuItem("Smali\u5DE5\u5177");
        mntmSmali.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new SmaliUi();
            }
        });
        menu.add(mntmSmali);

        JMenuItem mntmsdk = new JMenuItem("\u4E00\u952E\u77ED\u4EE3SDK");
        mntmsdk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new SMSToolsUi();
            }
        });
        menu.add(mntmsdk);

        menuItem_1 = new JMenuItem("\u67E5\u770B\u7B7E\u540D");
        menuItem_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new AndroidKey();
            }
        });
        menu.add(menuItem_1);

        JMenuItem mntmOnweay = new JMenuItem("\u4FEE\u6539\u4E07\u7EF4\u63D2\u4EF6\u5305");
        mntmOnweay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser(new File(new File("").getAbsolutePath()));
                chooser.showOpenDialog(null);
                File file = chooser.getSelectedFile();
                uFilePath.setText(file.getAbsolutePath());
                log.setText("正在修改万维插件包...");
                new OneWayTools(file);
                log.setText("修改万维成功，成功后文件将生成在反编译文件夹中");

            }
        });

        JMenuItem mntmapk = new JMenuItem("\u7B7E\u540DAPK");
        mntmapk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new ApkSignUi();
            }
        });
        menu.add(mntmapk);
        menu.add(mntmOnweay);

        JMenuItem mntmsdk_1 = new JMenuItem("\u4FEE\u6539\u7B2C\u4E09\u65B9SDK");
        mntmsdk_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new ModifySdkUi();
            }
        });
        menu.add(mntmsdk_1);

        JMenuItem csj=new JMenuItem("穿山甲资源包");
        csj.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ChuanShanJiaUi.main(null);
            }
        });
        menu.add(csj);


        mnBasetools = new JMenu("Base64\u5DE5\u5177");
        menuBar.add(mnBasetools);

        mntmbase = new JMenuItem("\u8F6CBase64");
        mntmbase.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser jFile = new JFileChooser(new File(new File("").getAbsolutePath()));
                jFile.showOpenDialog(null);
                File file = jFile.getSelectedFile();
                JarToBase.start(file.getAbsolutePath(), true);
            }
        });
        mnBasetools.add(mntmbase);

        mntmBase = new JMenuItem("Base64\u89E3\u7801");
        mntmBase.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser jFile = new JFileChooser(new File(new File("").getAbsolutePath()));
                jFile.showOpenDialog(AppMain.this);
                File file = jFile.getSelectedFile();
                JarToBase.start(file.getAbsolutePath(), false);
                log.setText("已解码");
            }
        });
        mnBasetools.add(mntmBase);

        setVisible(true);
    }
}
