package com.device.comm.mylibrary;

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

import com.android.pj11.PJ11UartJni;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;

import java.math.BigDecimal;
import java.math.RoundingMode;
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.yaseeGlucoseModuel;

public class RNM10GKUCommandHandler  extends RNM10BaseCommandHandler{
    final private static String TAG = "RN_M10_GLUCOSE_DEVICE";
    private Integer resultType = 0;

    public RNM10GKUCommandHandler(ReactApplicationContext context) {
        super(context);
    }

    @Override
    protected  void deviceStatusChanged(int status){
        if(status == KEYCODE_PLUG_OUT_UART){
            sendStatus("设备未连接",0x00,0);
        }else if(status == KEYCODE_PLUG_IN_UART){
            sendStatus("请插入试纸",0x01,0);
        }
    }
    @Override
    protected void sendInitStatus(){
        sendStatus("请插入试纸",0x01,0);
    }
    @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);

            }
            break;
            case 0x82:{
                //休眠
                Log.d(TAG,"sleep command is 0x82 "+(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 0x86:{
                //吸血
                Log.d(TAG,"command is "+(data[3]&0xff));
                sendStatus("检测到血样",command,0);
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x86);
                    }
                },100);
            }
            break;
            case 0x87:{
                //倒计时
                Log.d(TAG,"command is "+(data[3]&0xff));
                sendStatus("检测倒计时："+(data[5]&0xff),command,(data[5]&0xff));
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        sendAck((byte)0x87);
                    }
                },100);
            }
            break;
            case 0x88:{
                //血糖结果
                Log.d(TAG,"command is "+(data[3]&0xff));
                int value = (data[8]&0xff)*256+(data[7]&0xff);
                sendStatus("",command,0);
                sendValue(value);
                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 0x8c "+(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;
        }
    }
    @Override
    protected 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 = "";
        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";
        }

        // 如果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 value){
//        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String curDateString = dateFormatter.format(curDate);
        String displayValue = "";
        String type = "";
        String eventName = "";
        if(resultType == 0x10){
            displayValue =  new BigDecimal(value*0.055).setScale(1, RoundingMode.HALF_UP).toString();
            type = "glucose";
            eventName = "RESULT_BT_DEVICE";
        }else if(resultType == 0x40){
            displayValue =new BigDecimal((float)(value/168.1)).setScale(3,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(1000)).toString();
            type = "adid";
            eventName = "RESULT_ACID";
        }else{
            displayValue =  new BigDecimal(value*0.1).setScale(1, RoundingMode.HALF_UP).toString();
            type = "ketone";
            eventName = "RESULT_BT_DEVICE";
        }
        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("value", displayValue);
        map.putString("displayValue", displayValue);
        map.putString("resultType", type);

        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);
    }
}
