package com.example.iot_controlhost.ui.dialog;

import android.content.Context;
import android.transition.Fade;
import android.transition.TransitionManager;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;

import com.example.iot_controlhost.R;
import com.example.iot_controlhost.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogAirConditionBinding;
import com.example.iot_controlhost.model.controller.AirConditionInfrared;
import com.example.iot_controlhost.model.thread.QueueIOUITask;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.control.infrared.MyInfraredUtils;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.log.UserLog;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;

import android_serialport_api.SerialPortUtil;

/**
 * 空调遥控器
 */
public class AirDialog extends BaseDialog<DialogAirConditionBinding> {
    AirConditionInfrared air;

    public AirDialog(@NonNull Context mContext, AirConditionInfrared air) {
        super(mContext);
        this.air = air;
        refreshAir();
        //打开串口
        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
            errorTips("串口打开失败");
        }
        binding.tvTitle.setText("空调—" + air.getName());
        binding.modeHeat.setOnClickListener(v -> changeAirCondition(0));
        binding.modeAuto.setOnClickListener(v -> changeAirCondition(1));
        binding.modeCold.setOnClickListener(v -> changeAirCondition(2));
        binding.modeDehumidify.setOnClickListener(v -> changeAirCondition(-1));
        binding.btnAirPower.setOnClickListener(v -> changeAirCondition(3));
        binding.btnAirPlus.setOnClickListener(v -> changeAirCondition(4));
        binding.btnAirReduce.setOnClickListener(v -> changeAirCondition(5));
    }

    public void refreshAir() {
        TransitionManager.beginDelayedTransition(binding.ll, new Fade());
        binding.ivSelHeat.setVisibility(air.getMode() == AirConditionInfrared.HEAT ? View.VISIBLE : View.INVISIBLE);
        binding.ivSelAuto.setVisibility(air.getMode() == AirConditionInfrared.AUTO ? View.VISIBLE : View.INVISIBLE);
        binding.ivSelCold.setVisibility(air.getMode() == AirConditionInfrared.COLD ? View.VISIBLE : View.INVISIBLE);
        binding.ivSelDehumidify.setVisibility(air.getMode() == AirConditionInfrared.DEHUMIDIFY ? View.VISIBLE : View.INVISIBLE);
        binding.airModeState.setText(air.getModeName());
        binding.ivModeState.setImageDrawable(air.getMode() == AirConditionInfrared.HEAT ?
                mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.heat_dark : R.mipmap.heat) : air.getMode() == AirConditionInfrared.AUTO ?
                mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.auto_dark : R.mipmap.auto) :
                mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.cold_dark : R.mipmap.cold));
        binding.modeHeat.setImageDrawable(AppCompatResources.getDrawable(mContext, RoomSetting.isDarkTheme() ? R.mipmap.heat_dark : R.mipmap.heat));
        binding.modeAuto.setImageDrawable(mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.auto_dark : R.mipmap.auto));
        binding.modeCold.setImageDrawable(mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.cold_dark : R.mipmap.cold));
        binding.modeDehumidify.setImageDrawable(mContext.getDrawable(RoomSetting.isDarkTheme() ? R.mipmap.cold_dark : R.mipmap.cold));
        if (air.isPowerSupply()) {
            binding.btnAirPower.setImageDrawable(mContext.getDrawable(R.mipmap.open));
            binding.tvAirTemperature.setText(String.valueOf(air.getTemperature()));
        } else {
            binding.btnAirPower.setImageDrawable(mContext.getDrawable(R.mipmap.close));
            binding.tvAirTemperature.setText("—");
        }
    }

    /**
     * @param type -1:变更模式-除湿 0：变更模式-制热 1：变更模式-自动 2：变更模式-制冷 3：反转开关 4：温度+ 5：温度-
     */
    public void changeAirCondition(int type) {
        DialogUtil.showLoadingDialog(mContext, mContext.getString(R.string.in_operate_air_condition));
        MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Boolean>() {
            @Override
            public Boolean doInQueueThread() throws Exception {
                switch (type) {
                    case -1:
                        return air.setAirConditionMode(AirConditionInfrared.DEHUMIDIFY);
                    case 0:
                    case 1:
                    case 2:
                        return air.setAirConditionMode(type);
                    case 3:
                        boolean res;
                        if(air.isPowerSupply()){
                            res = air.setPowerSupply(false);
                        }else{
                            // 修复手动开电源时，没有设为目标温度和模式。
                            res = air.setAirCondition(air.getMode(),air.getTemperature());
                        }
                        return res;
                    case 4:
                        return air.setAirConditionTemperature(air.getTemperature() + 1);
                    case 5:
                        return air.setAirConditionTemperature(air.getTemperature() - 1);
                }
                return false;
            }

            @Override
            public void doInUIThread(Boolean result) {
                if (result) {
                    successTips(air.getState());
                    UserLog.operate("本机屏幕", "空调操作成功：" + air.getState());
                } else {
                    String errorTips = "手动：操作空调失败";
                    if (RoomSetting.isAirConditionForceClose()) {
                        errorTips += "，在消毒期间无法开启空调";
                    }
                    errorTips(errorTips);
                    UserLog.operateError("本机屏幕", errorTips);
                }
                refreshAir();
                DialogUtil.hideLoadingDialog();
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (RoomSetting.getMode() == 0) {
            //更新手动模式UI
            RxBusUtils.get().post(RxTag.UPDATE_MANUAL, 0);
        } else if (RoomSetting.getMode() == 1) {
            //更新自动模式UI
            RxBusUtils.get().post(RxTag.UPDATE_AUTO, 2);
        }
    }
}
