package com.develop.food.base.utils;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.PowerManager;

import com.google.gson.Gson;
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevModes;
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus;
import com.kuyuntech.cofarcooking.device.sdk.constant.core.HeatModes;
import com.kuyuntech.cofarcooking.device.sdk.constant.core.MotorDirections;
import com.kuyuntech.cofarcooking.device.sdk.devmode.core.BaseDevMode;
import com.kuyuntech.cofarcooking.device.sdk.eventbus.core.DevInfo;
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK;
import com.tuya.smartai.iot_sdk.DPEvent;
import com.tuya.smartai.iot_sdk.IoTSDKManager;
import com.tuya.smartai.iot_sdk.Log;
import com.tuya.smartai.iot_sdk.UpgradeEventCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

public class TuyaUtils {
    public static Context context;
    public static String version;
    public static final String TAG = "TUYA";
    public static  String mPid = "dquk8axtyy72c1ap";
    public static  String mUid = "uuid50e9e0c707553116";
    public static  String mAk = "MJhcxmQ6LeZDj1tNu6F5kqK5aQJfpdOb";
    public static  String qrcodeUrl =  "";
    public static IoTSDKManager ioTSDKManager = null;
    
    public static boolean init = false;

    public static void output(String text) {
        Log.d(TAG, text);
    }


    public static Integer parse(int e) {

        if(e <= 0){
            return  0;
        }

        StringBuilder a = new StringBuilder("1");
        for (int i = 0; i < e -1; i++) {
            a.append("0");
        }
        return Integer.parseInt(a.toString(),2);
    }

    public static void  uploadData(){
        if(ioTSDKManager == null || !init){
            return;
        }

        int devMode = -1;
        if(DevModes.SOUP.equals(CofarSDK.devInfo().getDevMode())){
            devMode = 0;
        }else if (DevModes.AIR_FRYER.equals(CofarSDK.devInfo().getDevMode())){
            devMode = 4;
        }

        DevInfo info = CofarSDK.devInfo();

        BaseDevMode mode = info.getMode();

        DPEvent[] dpEvents = new DPEvent[]{
          new DPEvent(TuyaDps.DEV_MODE,(byte) DPEvent.Type.PROP_VALUE,devMode,0),
          new DPEvent(TuyaDps.CURRENT_PRESSURE_COOKER,(byte) DPEvent.Type.PROP_VALUE,-1,0),
          new DPEvent(TuyaDps.TARGET_PRESSURE_COOKER,(byte) DPEvent.Type.PROP_VALUE,-1,-1),
          new DPEvent(TuyaDps.TARGET_TIME,(byte) DPEvent.Type.PROP_VALUE,info.getTargetTimeBuffer() != -1 ? info.getTargetTimeBuffer() : info.getTargetTime(),0),
          new DPEvent(TuyaDps.REMAIN_TIME_O,(byte) DPEvent.Type.PROP_VALUE,info.getRemainTime(),0),
          new DPEvent(TuyaDps.ERROR_CODE,(byte) DPEvent.Type.PROP_VALUE,(int)info.getErrCode(),0),
          new DPEvent(TuyaDps.TY_ERROR_CODE,(byte) DPEvent.Type.PROP_BITMAP, parse(info.getErrCode()),0),
          new DPEvent(TuyaDps.WORK_STATE,(byte) DPEvent.Type.PROP_VALUE,info.getStatus(),0),
          new DPEvent(TuyaDps.MOTOR_GEAR,(byte) DPEvent.Type.PROP_VALUE,(int)(info.getMotorGearBuffer() != -1 ? info.getMotorGearBuffer() : info.getMotorGear()),0),
          new DPEvent(TuyaDps.MOTOR_DIRECTION,(byte) DPEvent.Type.PROP_VALUE,(int)(info.getMotorDirectionBuffer() != -1 ? info.getMotorDirectionBuffer():info.getMotorDirection()),0),
          new DPEvent(TuyaDps.SPRAY_WATER,(byte) DPEvent.Type.PROP_VALUE,(int)(info.getWaterGearBuffer() != -1 ? info.getWaterGearBuffer() : info.getWaterGear()),0),
          new DPEvent(TuyaDps.WIND_SPEED,(byte) DPEvent.Type.PROP_VALUE,1,0),
          new DPEvent(TuyaDps.TARGET_TEMP,(byte) DPEvent.Type.PROP_VALUE,(int)(info.getTargetTempBuffer() != -1 ? info.getTargetTempBuffer():info.getTargetTemp()),0),
          new DPEvent(TuyaDps.CURRENT_TEMP,(byte) DPEvent.Type.PROP_VALUE,(int)CofarUtils.parseTemp(info.getTemp()),0),
          new DPEvent(TuyaDps.POT_CLOVER_STATUS,(byte) DPEvent.Type.PROP_VALUE,(int)info.getPotCloverStatus(),0),
          new DPEvent(TuyaDps.POT_STATUS,(byte) DPEvent.Type.PROP_VALUE,(int)info.getPotStatus(),0),
          new DPEvent(TuyaDps.DEV_READY,(byte) DPEvent.Type.PROP_VALUE,CommonUtils.INSTANCE.devReady() ? 0 : 1,0),
          new DPEvent(TuyaDps.MAX_TIME,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMaxTime(),0),
          new DPEvent(TuyaDps.MIN_TIME,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMinTime(),0),
          new DPEvent(TuyaDps.MAX_TEMP,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMaxTemp(),0),
          new DPEvent(TuyaDps.MIN_TEMP,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMinTemp(),0),
          new DPEvent(TuyaDps.MAX_MOTOR_GEAR,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMaxMotorGear(),0),
          new DPEvent(TuyaDps.MIN_MOTOR_GEAR,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMinMotorGear(),0),
          new DPEvent(TuyaDps.MAX_SPRAY_WATER,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMaxWaterGear(),0),
          new DPEvent(TuyaDps.MIN_MOTOR_GEAR,(byte) DPEvent.Type.PROP_VALUE,mode == null ? 0 : mode.getMinMotorGear(),0),


        };



        ioTSDKManager.sendDP(dpEvents);
    }

    public static void cancelBind(){
        init = false;
        if (ioTSDKManager!=null){
            ioTSDKManager.reset();
        }



    }


    public static void baseInitSDK(Context ctx,String version) {

        ioTSDKManager = new IoTSDKManager(ctx) {
            @Override
            protected boolean isOffline() {
                //实现自定义网络监测
                Log.d(TAG, "isOffline: " + super.isOffline());
                return super.isOffline();
            }
        };

        output("固件版本：" + version);

        output("init sdk：" + mPid + "/" + mUid + "/" + mAk);

        //注意：这里的pid等配置读取自local.properties文件，不能直接使用。请填写你自己的配置！
        ioTSDKManager.initSDK("/sdcard/tuya_iot/", mPid
                , mUid, mAk, version, new IoTSDKManager.IoTCallback() {

                    @Override
                    public void onDpEvent(DPEvent event) {

                        TuyaEvent a = new TuyaEvent();
                        a.setType("test");
                        EventBus.getDefault().post(a);

                        if (event != null) {
                            output("收到 dp: " + event);

                            if(event.dpid == TuyaDps.RECIPE_NUM){
                                CommonUtils.INSTANCE.navigateToRemoteRecipe((String) event.value);
                            }

                            if(event.dpid == TuyaDps.DEV_READY){
                                CommonUtils.INSTANCE.navigateToAdaptedCooking();
                            }

                            if(event.dpid == TuyaDps.WORK_STATE){

                                if(DevStatus.STOP == (int)event.value){
                                    TuyaEvent e = new TuyaEvent();
                                    e.setType("stop");
                                    EventBus.getDefault().post(e);
                                }


                                if(DevStatus.PAUSE == (int)event.value){
                                    TuyaEvent e = new TuyaEvent();
                                    e.setType("pause");
                                    EventBus.getDefault().post(e);
                                }


                                if(DevStatus.RUNNING == (int)event.value){
                                    TuyaEvent e = new TuyaEvent();
                                    e.setType("start");
                                    EventBus.getDefault().post(e);
                                }
                            }


                            if(event.dpid == TuyaDps.TARGET_TEMP){
                                CofarSDK.cfgHeat((short) (int) event.value, HeatModes.PU_TONG);
                                TuyaEvent e = new TuyaEvent();
                                e.setType("change_temp");
                                EventBus.getDefault().post(e);
                            }

                            if(event.dpid == TuyaDps.TARGET_TIME){
                                CofarSDK.cfgTime( (int) event.value);
                                TuyaEvent e = new TuyaEvent();
                                e.setType("change_time");
                                EventBus.getDefault().post(e);
                            }

                            if(event.dpid == TuyaDps.MOTOR_DIRECTION){
                                CofarSDK.cfgMotorDirection((int) event.value == 0 ? MotorDirections.FORWARD:MotorDirections.REVERSE);
                            }

                            if(event.dpid == TuyaDps.MOTOR_GEAR){
                                CofarSDK.cfgMotorGear((byte) ((int)event.value & 0xFF));
                            }



                        }


                    }

                    @Override
                    public void onReset() {

                        ctx.getSharedPreferences("event_cache", MODE_PRIVATE).edit().clear().commit();
                        PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
                        pm.reboot("");

                    }

                    @Override
                    public void onShorturl(String urlJson) {
                        output("shorturl: " + urlJson);
                        Gson gson = new Gson();
                        Map d = gson.fromJson(urlJson, Map.class);
                        String url = (String) d.get("shortUrl");
                        qrcodeUrl = url;
                        MmkvUtils.INSTANCE.save("tuya_url",url);
                        EventBus.getDefault().post(new TuyaUtils());
                    }

                    @Override
                    public void onActive() {
                        output("onActive: devId-> " + ioTSDKManager.getDeviceId());
                        init = true;
                    }

                    @Override
                    public void onFirstActive() {
                        output("onFirstActive");
                    }

                    @Override
                    public void onMQTTStatusChanged(int status) {
                        output("onMQTTStatusChanged: " + status);

                        switch (status) {
                            case IoTSDKManager.STATUS_OFFLINE:
                                // 设备网络离线
                                break;
                            case IoTSDKManager.STATUS_MQTT_OFFLINE:
                                // 网络在线MQTT离线
                                break;
                            case IoTSDKManager.STATUS_MQTT_ONLINE:
                                // 网络在线MQTT在线

                                SharedPreferences sp = ctx.getSharedPreferences("event_cache", MODE_PRIVATE);

                                DPEvent[] events = ioTSDKManager.getEvents();

                                if (events != null) {
                                    for (DPEvent event : events) {
                                        if (event != null) {
                                            output(event.toString());
                                        }
                                    }
                                }
                                break;
                        }
                    }

//                    @Override
//                    public void onMqttMsg(int protocol, org.json.JSONObject msgObj) {
//
//                    }
                });

        ioTSDKManager.setUpgradeCallback(new UpgradeEventCallback() {
            @Override
            public void onUpgradeInfo(String s) {
                Log.w(TAG, "onUpgradeInfo: " + s);

                output("收到升级信息: " + s);

//                runOnUiThread(() -> upgradeDialog.show());

                ioTSDKManager.startUpgradeDownload();
            }

            @Override
            public void onUpgradeDownloadStart() {
                Log.w(TAG, "onUpgradeDownloadStart");

                output("开始升级下载");
            }

            @Override
            public void onUpgradeDownloadUpdate(int i) {
                Log.w(TAG, "onUpgradeDownloadUpdate: " + i);
            }

            @Override
            public void upgradeFileDownloadFinished(int result, String file) {
                Log.w(TAG, "upgradeFileDownloadFinished: " + result);

                output("下载完成：" + result + " / " + file);
            }
        });
    }

    public static void initSDK(Context ctx,String version) {
        context = ctx;
        version = version;
        //Log.init(ctx, "/sdcard/tuya_log/iot_demo/", 3);
        baseInitSDK(ctx,version);
    }


}
