package com.device.comm.mylibrary;

import android.content.Context;
import android.util.Log;

import com.btdevice.R;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.device.comm.mylibrary.RNYASEEGlucoseModule.KEYCODE_PLUG_IN_UART;
import static com.device.comm.mylibrary.RNYASEEGlucoseModule.KEYCODE_PLUG_OUT_UART;
import static com.device.comm.mylibrary.RNYASEEGlucoseModule.readDeviceStatus;
import static com.device.comm.mylibrary.RNYASEEGlucoseModule.uartState;
import static com.device.comm.mylibrary.RNYASEEGlucoseModule.yaseeGlucoseModuel;

public class RNM10LMCommandHandler extends RNM10BaseCommandHandler {
    final private static String TAG = "RN_M10_LM_MODULE";
    private Context mContext;
    private boolean isRunning = false;
    private byte[] LMCodeBuffer ;
    public RNM10LMCommandHandler(ReactApplicationContext context) {
        super(context);
        mContext = context;
        readLMCode();
    }


//   @Override
//   public void start(){
//        super.start();
//        isRunning = false;
//   }
    @Override
    protected void sendInitStatus(){
        sendStatus("正在连接设备",0x01,0);
    }
    @Override
    protected  void deviceStatusChanged(int status){
        if(status == KEYCODE_PLUG_OUT_UART){
            isRunning = false;
            sendStatus("设备未连接",0x00,0);
        }else if(status == KEYCODE_PLUG_IN_UART){
            sendStatus("正在连接设备",0x01,0);
            isRunning  = false;
        }
    }

    @Override
    protected CheckDeviceThread createCheckDeviceThread() {
        return new M10CheckDeviceThread();
    }

    private class M10CheckDeviceThread extends CheckDeviceThread {
        @Override
        public void run() {
            while (shouldRun) {
                if(isRunning){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                try {
                    String status = readDeviceStatus();
                    RNLog.d(TAG,"device status:"+status);
                    if(status.startsWith("0")){
                        Thread.sleep(1000);
                        continue;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                RNLog.d(TAG,"device uart status:"+uartState);
                if(uartState!=0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    continue;
                }
                sendHand();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    @Override
    public void commandHandler(byte[] data,int length){
        Log.d(TAG,"data length "+data.length);
        if(length == 4){
            Log.d(TAG,"awake "+(data[0]&0xff));
            if(((data[0]&0xff)== 0xaa) && ((data[1]&0xff)== 0x55) && ((data[2]&0xff)== 0xaa) && ((data[3]&0xff)== 0x55) ){
                yaseeGlucoseModuel.findDevice = false;
                sendStatus("正在连接设备",0x01,0);
                BleDevice device = BleDeviceManager.get(mContext).addSerialPortDevice(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC,ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE);
                long currentTime = System.currentTimeMillis()+(long)30*24*3600*1000;
                device.setDeviceDate(currentTime);
            }

            return;
        }

        if(!checkCommand(data)){
            return;
        }

        int command = data[3]&0xff;
        switch (command){
            case 0x80:{
                yaseeGlucoseModuel.findDevice = false;
                sendStatus("正在连接设备",command,0);
                BleDevice device = BleDeviceManager.get(mContext).addSerialPortDevice(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC,ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE);
                long currentTime = System.currentTimeMillis()+(long)30*24*3600*1000;
                device.setDeviceDate(currentTime);

                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x80);
                    }
                },100);
            }
            break;
            case 0x81:{
                Log.d(TAG,"command is "+(data[3]&0xff));
                yaseeGlucoseModuel.findDevice = true;
                sendStatus("正在连接设备",command,0);
                BleDevice device = BleDeviceManager.get(mContext).addSerialPortDevice(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC,ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE);
                long currentTime = System.currentTimeMillis()+(long)30*24*3600*1000;
                device.setDeviceDate(currentTime);
                //             sendStatus(data[i+4]&0xff);

                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        if(isRunning){
                            return;
                        }
                        sendHand();
                    }
                },300);
            }
            break;
            case 0x82:{
                //休眠
                Log.d(TAG,"sleep command is "+(data[3]&0xff));

                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendStatus("设备休眠，请重新插入试纸",0x82,0);
                    }
                },300);
                yaseeGlucoseModuel.findDevice = true;
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x82);
                    }
                },100);
            }
            break;
            case 0x83:{
                //插入试纸
                Log.d(TAG,"command is "+(data[3]&0xff));
                resultType = data[8]&0xff;
                if((data[7]&0xff) == 0x00){
                    //血糖试纸插入
                    sendStatus("请滴血",command,0);

                }else{
                    sendStatus("无效试纸插入",command,0);
                }


                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x83);
                    }
                },100);
            }
            break;
            case 0x85:{
                //插入试纸
                Log.d(TAG,"command is "+(data[3]&0xff));
                isRunning = true;
                yaseeGlucoseModuel.findDevice = true;

                switch(data[5]){
                    case 0x00:
                        // 新试纸
                        sendStatus("检测到新试纸", command, 0x00);
                        break;
                    case 0x01:
                        // 无试纸
                        sendStatus("请插入试纸", command, 0x01);
                        break;
                    case 0x02:
                        // 无效试纸
                        sendStatus("无效试纸", command, 0x02);
                        break;
                    case 0x03:
                        // 用过的试纸
                        sendStatus("用过的试纸", command, 0x03);
                        break;
                    case 0x04:
                        // 代码卡与试条不符
                        sendStatus("代码卡与试条不符", command, 0x04);
                        break;
                    case 0x05:
                        // 请拨除试条
                        sendStatus("请拨除试条", command, 0x05);
                        break;
                    default:
                        // 未知状态
                        sendStatus("未知状态", command, -1);
                        break;
                }
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x85);
                    }
                },100);
            }
            break;
            case 0x86:{
                //吸血
                Log.d(TAG,"command is "+(data[3]&0xff));
                int status = data[5]&0xff;
                switch(status){
                    case 0:
                        // 正在等待滴血
                        sendStatus("正在等待滴血", command, 0);
                        break;
                    case 1:
                        // 正在检测滴血量
                        sendStatus("正在检测滴血量", command, 1);
                        break;
                    case 2:
                        // 滴血完成
                        sendStatus("滴血完成", command, 2);
                        break;
                    case 3:
                        // 滴血不足（血脂）
                        sendStatus("滴血不足", command, 3);
                        break;
                    default:
                        // 未知状态
                        sendStatus("未知状态", command, -1);
                        break;
                }
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x86);
                    }
                },100);
            }
            break;
            case 0x87:{
                //倒计时
                Log.d(TAG,"command is "+(data[3]&0xff));
                int countDownValue = data[5]&0xff;
                String statusMessage = "";

                if(countDownValue >= 250){
                    switch(countDownValue){
                        case 250:
                            statusMessage = "提前结束了";
                            break;
                        case 251:
                            statusMessage = "超时结束了";
                            break;
                        case 252:
                            statusMessage = "用户中断测量";
                            break;
                        case 253:
                            statusMessage = "测试过程中，用户拨条了";
                            break;
                        default:
                            statusMessage = "未知状态：" + countDownValue;
                    }
                }else{
                    statusMessage = "检测计时：" + countDownValue;
                }

                sendStatus(statusMessage, command, countDownValue);

                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x87);
                    }
                },100);
            }
            break;
            case 0x88:{
                //血糖结果
                Log.d(TAG,"command is "+(data[3]&0xff));
                // AA 55 1E 88 04
                // 00
                // 01 01 01 02 00
                // 1A 2E 20 7B 24 A9 00 00 00 00
                // 68 E0 67 6E 3F 91 00 00 FF FE
                // 07 2B
                int HDLValue = (data[17]&0xff)*256+(data[16]&0xff);
                int TGValue = (data[19]&0xff)*256+(data[18]&0xff);
                int TCValue = (data[21]&0xff)*256+(data[20]&0xff);
                int LDLValue = (data[23]&0xff)*256+(data[22]&0xff);
                int TCDivHDLValue = (data[25]&0xff)*256+(data[24]&0xff);
//                sendStatus("",command,0);
                sendValue(HDLValue,TGValue,TCValue,LDLValue,TCDivHDLValue);
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x88);
                    }
                },100);
            }
            break;
            case 0x8b:{
                //进入错误模式
                Log.d(TAG,"command is "+(data[3]&0xff));
                sendErrorValue(data[7]&0xff);
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x8b);
                    }
                },100);
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendSleep();
                    }
                },10*1000);
            }
            break;
            case 0x8c:{
                Log.d(TAG,"command is "+(data[3]&0xff));
                yaseeGlucoseModuel.findDevice = true;
                sendStatus("请插入试纸",command,0);
                BleDevice device = BleDeviceManager.get(mContext).addSerialPortDevice(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC,ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE);
                long currentTime = System.currentTimeMillis()+(long)30*24*3600*1000;
                device.setDeviceDate(currentTime);
                //             sendStatus(data[i+4]&0xff);

                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendHand();
                    }
                },300);
            }
            break;
        }
    }

    public void sendStatus(String status,Integer command,Integer extraParameter){
//        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String curDateString = dateFormatter.format(curDate);
        String type = "lipid";
        String eventName = "STATUS_LIPID_DEVICE";

        // 如果command是0x00或0x01，强制将type设置为"M10"
        if (command == 0x00 || command == 0x01 || command == 0x82) {
            type = "M10";
            eventName = "STATUS_M10_DEVICE";
        }

        WritableMap map = Arguments.createMap();
        map.putString("deviceName", "one");
        map.putString("deviceMac", "no");
        map.putString("deviceStatusDescription", "测量成功");
        map.putString("deviceStatus", "result");
        map.putString("time", curDateString);
        map.putString("deviceTime", curDateString);
        map.putString("status", status);
        map.putString("resultType", type);
        map.putInt("command",command);
        map.putInt("extraParameter", extraParameter);
        RNLog.d(TAG,"send map:"+map);
        mEventManager.sendCustomEvent(eventName, map);
    }


    public void sendValue(int HDLValue, int TGValue, int TCValue, int LDLValue, int TCDivHDLValue){
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String curDateString = dateFormatter.format(curDate);
        String type = "lipid";
        String eventName = "RESULT_M10_LM";

        WritableMap map = Arguments.createMap();
        map.putString("deviceName", "one");
        map.putString("deviceMac", ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC);
        map.putString("deviceStatusDescription", "测量成功");
        map.putString("deviceStatus", "result");
        map.putString("time", curDateString);
        map.putString("deviceTime", curDateString);
        map.putString("resultType", type);
        map.putInt("HDLValue", HDLValue);
        map.putInt("TGValue", TGValue);
        map.putInt("TCValue", TCValue);
        map.putInt("LDLValue", LDLValue);
        map.putInt("TCDivHDLValue", TCDivHDLValue);

        RNLog.d(TAG,"send value:"+map);

        mEventManager.sendCustomEvent(eventName, map);
    }

    public void sendErrorValue(int value){
        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String curDateString = formatter.format(curDate);
        String errorMessage = "";
        switch (value){
            case 0x03:
                errorMessage="EEPROM读错误";
                break;
            case 0x04:
                errorMessage="EEPROM写错误";
                break;
            case 0x17:
                errorMessage="错误试纸";
                break;
            case 0x18:
                errorMessage="无效试纸";
                break;
            case 0x2d:
                errorMessage="测试过程中断";
                break;
            case 0x36:
                errorMessage="温度越限";
                break;
            case 0x3e:
                errorMessage="参数错误";
                break;
            case 0x4d:
                errorMessage="通讯错误";
                break;
        }

        if(errorMessage.equals("")){
            return;
        }

        String hex = Integer.toHexString(value);
        if (hex.length() == 1) {
            hex = '0' + hex ;
        }
        errorMessage = errorMessage + " " +  hex.toUpperCase();

        String type = "";
        String eventName = "";
        if(resultType == 0x10){
            type = "glucose";
            eventName = "STATUS_GLUCOSE_DEVICE";
        }else if(resultType == 0x40){
            type = "acid";
            eventName = "STATUS_ACID_DEVICE";
        }else{
            type = "ketone";
            eventName = "STATUS_KETONE_DEVICE";
        }

        WritableMap map = Arguments.createMap();
        map.putString("deviceName", "one");
        map.putString("deviceMac", "no");
        map.putString("deviceStatusDescription", "测量成功");
        map.putString("deviceStatus", "result");
        map.putString("time", curDateString);
        map.putString("deviceTime", curDateString);
        map.putString("errorMessage",errorMessage);
        map.putString("status",errorMessage);
        map.putString("resultType", type);


        mEventManager.sendCustomEvent(eventName, map);
    }

    private void readLMCode(){
//        try {
//            InputStream inputStream = mContext.getResources().openRawResource(R.raw.lm_code);
//            byte[] buffer = new byte[inputStream.available()];
//            inputStream.read(buffer);
//            RNLog.d(TAG,"bin:"+HexUtils.bytesToHexString(buffer));
//            RNLog.d(TAG,"length: "+buffer.length);
//            inputStream.close();
//            // 现在，buffer中包含了文件的内容
//            LMCodeBuffer = buffer;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
