package com.hh.lib_infrared;

import static com.hh.lib_base.Constants.Ampe.EVENT_INFRARED_INDUCTION_LISTENER;
import static com.hh.lib_base.Constants.LogcatValue.LOG_NODE_INFRARED_INDUCTION;
import static com.hh.lib_base.Constants.LogcatValue.WARP;
import static com.hh.lib_base.Constants.Value.INDUCTION_CODE;
import static com.hh.lib_base.Constants.Value.INDUCTION_INSTRUCT;
import static com.hh.lib_base.Constants.Value.INDUCTION_PEOPLE_NO;
import static com.hh.lib_base.Constants.Value.INDUCTION_PEOPLE_YES;
import static com.hh.lib_base.Constants.Value.TIME_INDUCTION_INTERVAL;

import android.content.Context;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_ampe.utils.AromeInvoker;
import com.hh.lib_ampe.utils.MyTypeToken;
import com.hh.lib_base.Constants;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_infrared.bean.AmpeRequestInfraredBean;
import com.hh.lib_serialport.MyFunc;
import com.hh.lib_serialport.SerialHelper;
import com.hh.lib_serialport.bean.ComBean;

import org.json.JSONObject;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author xwh
 * time 2024/9/6
 * Description: 红外线调用器
 **/
public class InfraredInvoker {

    private volatile static InfraredInvoker invoker;
    private volatile boolean isStartInfrared = false; //是否启动红外感应读取
    private SerialHelper comPortInfraredInduction;
    private Timer timer;
    private TimerTask inductionTimerTask;

    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 红外线功能交互入口
     **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        switch (dataBean.getAction()) {
            case Constants.Ampe.ACTION_START_INFRARED_INDUCTION_LISTENER: //TODO 开启红外线感应
                startInfraredInductionListener(dataBean, bridgeCallback);
                break;
            case Constants.Ampe.ACTION_STOP_INFRARED_INDUCTION_LISTENER: //TODO 关闭红外线感应
                stopInfraredInductionListener(dataBean, bridgeCallback);
                break;
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/9/6
     * Description: 启动红外感应
     *
    **/
    private void startInfraredInductionListener(BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        BaseAmpeRequestBean<AmpeRequestInfraredBean> newBean = MyTypeToken
                .toBaseAmpeRequestBean(dataBean, AmpeRequestInfraredBean.class);
        if (newBean == null) {
            return;
        }
        int infraredInductionIntervalTime = TIME_INDUCTION_INTERVAL;
        if (newBean.getParams() != null) {
            infraredInductionIntervalTime = newBean.getParams().getIntervalTime();
        }
        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(newBean.getAction());
        bean.setEvent(newBean.getEvent());
        bean.setTaskId(newBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_INFRARED_INDUCTION,
                    "---" + Constants.Ampe.ACTION_START_INFRARED_INDUCTION_LISTENER, logLine, "启动红外线感应成功！");
        } catch (Exception e) {
            AppLogUtils.e("onCalled--e" + e.toString());
        }
        // 发送指令
        sendInfraredCommand(comPortInfraredInduction, infraredInductionIntervalTime);

    }

    /**
     *
     * @author xwh
     * Time 2024/9/6
     * Description: 停止红外感应
     *
    **/
    private void stopInfraredInductionListener(BaseAmpeRequestBean dataBean,
                                               AromeServiceInvoker.BridgeCallback bridgeCallback) {
        isStartInfrared = false;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (dataBean == null) {
            return;
        }
        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(dataBean.getAction());
        bean.setEvent(dataBean.getEvent());
        bean.setTaskId(dataBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_INFRARED_INDUCTION,
                    "---" + Constants.Ampe.ACTION_START_INFRARED_INDUCTION_LISTENER, logLine, "关闭红外线感应成功！");
        } catch (Exception e) {
            AppLogUtils.e("onCalled--e" + e.toString());
        }
    }

    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 发送红外感应指令
     **/
    public synchronized void sendInfraredCommand(SerialHelper comPort, Integer infraredInductionIntervalTime) {
        if (comPort == null) {
            return;
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        inductionTimerTask = new TimerTask() {
            @Override
            public void run() {
                AppLogUtils.i("红外感应发送");
                // 转换数据后发送
                comPort.send(INDUCTION_INSTRUCT.getBytes());

            }
        };
        isStartInfrared = true;
        timer.schedule(inductionTimerTask, 1000, infraredInductionIntervalTime);


    }


    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 启动红外线串口
     **/
    private void startSeriaInfrared() {
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION
                , "---", logLine, "初始化---开始打开串口");
        InfraredSerialControl sc = new InfraredSerialControl();
        String pat = "";
        String deviceModel = DeviceUtils.getDeviceModel();
        if (deviceModel.equals(Constants.DeviceModel.T1YB01)) {
            pat = "/dev/ttysWK2";
        } else if (deviceModel.equals(Constants.DeviceModel.F10)) {
            pat = "/dev/ttyHSL2";
        }
        AppLogUtils.e("--------------pat串口路径  " + pat);


        // 设置串口路径
        sc.setPort(pat);
        // 波特率
        sc.setBaudRate("9600");
        // 打开红外感应
        OpenInductionLightComPort(sc);

    }


    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 打开红外线串口
     **/
    public void OpenInductionLightComPort(SerialHelper comPort) {
        try {
            comPort.open();
            this.comPortInfraredInduction = comPort;
//            sendInductionInstruct(comPort);

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine11 = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine11, "初始化---打开串口成功");

        } catch (SecurityException e) {
            AppLogUtils.e("-----------打开串口失败:没有串口读/写权限");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine, "初始化---打开串口失败:没有串口读/写权限");

        } catch (IOException e) {
            AppLogUtils.e("-----------打开串口失败:未知错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine, "初始化---打开串口失败:未知错误");

        } catch (InvalidParameterException e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine, "初始化---打开串口失败:参数错误");
        } catch (UnsatisfiedLinkError e2) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine, "初始化---打开串口失败:串口地址不存在");
            return;
        } catch (Exception e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_INFRARED_INDUCTION, "---",
                    logLine, "初始化---打开串口失败:"+e.toString());
            return;
        }
    }


    public class InfraredSerialControl extends SerialHelper {
        public InfraredSerialControl() {
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            AppLogUtils.e("-----------原始数据 bRec  " + new Gson().toJson(ComRecData.bRec));
            AppLogUtils.e("-------数据处理后  " + MyFunc.ByteArrToHex(ComRecData.bRec));

//            String str = new String(ComRecData.bRec, java.nio.charset.StandardCharsets.UTF_8);
//            AppLogUtils.e("-------数据Str  " +str);


            String result = new String(ComRecData.bRec, java.nio.charset.StandardCharsets.UTF_8);
            AppLogUtils.e("----------inductionLightQueueList结果bRec  " + result);

            String handleResult = "";
            if (result.equals(INDUCTION_PEOPLE_YES)) {
                handleResult = "1";
            } else if (result.equals(INDUCTION_PEOPLE_NO)) {
                handleResult = "0";
            } else {
                //
                handleResult = "-1";
            }

            AppLogUtils.e("isCloseInfraredInductionMessage:" + isStartInfrared);

            if (isStartInfrared) {
                // 准备数据发送
                JSONObject object = new JSONObject();
                try {
                    // 勿动key，对外的文档key
                    object.put(INDUCTION_CODE, handleResult);
                } catch (Throwable t) {

                }
                if (AromeInvoker.getAromeInvoker() != null) {
                    // 主动推送给小程序
                    AromeInvoker.getAromeInvoker().sendMessageToApplet(EVENT_INFRARED_INDUCTION_LISTENER,
                            object.toString());
                }
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_INFRARED_INDUCTION + "结果";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("原始数据 = ").append(new Gson().toJson(ComRecData.bRec)).append(WARP)
                    .append("原始数据MyFunc转换 = ").append(MyFunc.ByteArrToHex(ComRecData.bRec))
                    .append("原始数据转换result = ").append(result);
            UploadLogUtils.sendLogs(false,logNode, EVENT_INFRARED_INDUCTION_LISTENER, logLine, logContentSb.toString());

        }

        //尝试进行转换
        @Override
        protected void DoQueue() {

        }

    }

    public void onRelease() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (comPortInfraredInduction != null) {
            comPortInfraredInduction.close();
            comPortInfraredInduction = null;
        }
        invoker = null;

    }

    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 初始化启动红外线
     **/
    public void initInfrared() {
        startSeriaInfrared();
    }

    public static InfraredInvoker getInstance() {
        if (invoker == null) {
            synchronized (InfraredInvoker.class) {
                if (invoker == null) {
                    invoker = new InfraredInvoker();

                }
            }
        }
        return invoker;
    }

}
