package com.yutou.jianr_mg.services;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.bigzhao.jianrmagicbox.aidl.IMagicBoxBinder;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Databases.JianRDataDataBase;
import com.yutou.jianr_mg.Tools.JianRUtils;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.views.WarView;

import org.json.JSONObject;

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

import Interfaces.MagicBoxInterface;

import static android.content.Context.BIND_AUTO_CREATE;

public class MagicBoxService {
    private JSONObject order = null;
    private static MagicBoxService magicBoxService = null;
    private MagicBoxInterface magicBoxInterface;
    private JSONObject dealNode, getWarResult;
    private boolean isClose = true, saveData = false;
    private String dataType, dataName;


    private MagicBoxService() {
        initMagicBox();
    }

    public void setSaveData(boolean saveData, String dataName, String dataType) {
        this.saveData = saveData;
        this.dataName = dataName;
        this.dataType = dataType;
    }

    public static MagicBoxService init() {
        JianRUtils.readClientVersionIsbigzhao(Application.application);
        if (!Utils.getApplicationPackName(Application.application, AppData.magicPackageName)) {
            System.out.println("没有安装客户端");
            return null;
        }
        if (magicBoxService == null) {
            magicBoxService = new MagicBoxService();
        }
        return magicBoxService;
    }

    private ServiceConnection connection;

    private void initMagicBox() {
        System.out.println("绑定大钊客户端");
        isClose = false;
        connection = new ServiceConnection() {
            JianRDataDataBase dataBase;

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                System.out.println("链接大钊客户端");
                if (!Utils.testStringIsNull(dataName, dataType)) {
                    dataBase = JianRDataDataBase.init();
                }
                dataBase = JianRDataDataBase.init();
                IMagicBoxBinder boxBinder = IMagicBoxBinder.Stub.asInterface(iBinder);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (isClose) {
                            System.out.println("关闭连接");
                            cancel();
                            return;
                        }
                        if (order != null && !order.isNull("action")) {
                            try {
                                System.out.println("提交参数 action:" + order.getString("action") + " args:" + JSON.toJSONString(order.get("args")));
                            } catch (Exception ignored) {
                            }
                            try {
                                if (order.getString("action").equals("getVersion")) {
                                    magicBoxInterface.getData(boxBinder.getVersion() + "");
                                } else {
                                    magicBoxInterface.getData(boxBinder.action_remote(order.getString("action"), (String[]) order.get("args")));
                                }
                            } catch (Exception e) {
                                Application.application.unbindService(connection);
                                isClose = true;
                                cancel();
                            }
                        }
                        try {
                            String str = boxBinder.action_remote("getLastLog", new String[]{"DealNode"});
                            if (str != null) {
                                try {
                                    dealNode = new JSONObject(str);
                                    if (dataBase != null && saveData) {
                                        dataBase.addData(dataName, dealNode);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            String str2 = boxBinder.action_remote("getLastLog", new String[]{"GetWarResult"});
                            if (str2 != null) {
                                try {
                                    getWarResult = new JSONObject(str2);
                                    if (dataBase != null && saveData) {
                                        long id = dataBase.addData(dataName, getWarResult);
                                        getWarResult.put("dataId", id);
                                        if (id != -1)
                                            dataBase.addDrop(getWarResult);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            JSONObject json=new JSONObject(),json2=new JSONObject();
                            if(str!=null){
                                json=new JSONObject(str);
                                json.put("type","DealNode");

                            }
                            if(str2!=null){
                                json2=new JSONObject(str2);
                                json2.put("type","GetWarResult");
                            }
                            if(listener!=null){
                                listener.getData(json.toString());
                                listener.getData(json2.toString());
                            }
                            if(interfaces!=null){
                                for (MagicBoxInterface boxInterface : interfaces) {
                                    boxInterface.getData(json.toString());
                                    boxInterface.getData(json2.toString());
                                }
                            }
                            // System.out.println("str = "+str);
                            // System.out.println("str2 = "+str2);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        order = null;
                    }
                }, 0, 500);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                System.out.println("大钊客户端连接失败:" + componentName.flattenToString());
                isClose = true;
            }
        };
        Intent intent = new Intent();
        intent.setAction(com.bigzhao.jianrmagicbox.IMagicBoxBinder.ACTION_SERVICE);
        intent.setPackage(AppData.magicPackageName);
        Application.application.bindService(intent, connection, BIND_AUTO_CREATE);
    }

    public void startService() {
        try {
            Application.application.unbindService(connection);
            Intent intent = new Intent();
            intent.setAction(com.bigzhao.jianrmagicbox.IMagicBoxBinder.ACTION_SERVICE);
            intent.setPackage(AppData.magicPackageName);
            boolean tmp = Application.application.bindService(intent, connection, BIND_AUTO_CREATE);
            System.out.println("重新绑定结果：" + tmp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOrder(JSONObject order, MagicBoxInterface boxInterface) {
        if (isClose) {
            initMagicBox();
        }
        this.order = order;
        this.magicBoxInterface = boxInterface;
    }
    private List<MagicBoxInterface> interfaces;
    public void addInterface(MagicBoxInterface magicBoxInterface){
        if(interfaces==null){
            interfaces=new ArrayList<>();
        }
        interfaces.add(magicBoxInterface);

    }

    public void clearOrder() {
        order = null;
    }

    public JSONObject getDealNode() {
        return dealNode;
    }

    public JSONObject getGetWarResult() {
        return getWarResult;
    }

    public void close() {
        isClose = true;
    }

    private void saveData(JSONObject json, String fileName) {
        try {
            File file = new File(Utils.getSDCardPath() + "/" + fileName + ".txt");
            PrintWriter writer = new PrintWriter(file);
            writer.write(json.toString());
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private MagicBoxInterface listener=null;
    void setOnListener(MagicBoxInterface boxInterface) {
        this.listener=boxInterface;
    }
}
