package com.example.iot_controlhost.adapter;

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

import com.example.iot_controlhost.R;
import com.example.iot_controlhost.base.BaseRecyclerAdapter;
import com.example.iot_controlhost.databinding.ItemControllerAutoBinding;
import com.example.iot_controlhost.model.Result;
import com.example.iot_controlhost.model.controller.relay.Relay;
import com.example.iot_controlhost.model.sensor.GasSensor;
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.global.AutoModelSet;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSensor;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.SpinnerList;
import com.example.iot_controlhost.utils.log.UserLog;

import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * 手动控制继电器下的设备
 * 用于主界面显示
 *
 * @Author：DuanKaiji
 */
public class AutoControllerAdapter extends BaseRecyclerAdapter<Relay, ItemControllerAutoBinding> {
    Context mContext;

    public AutoControllerAdapter(Context context, List<Relay> dataList, Class<ItemControllerAutoBinding> bindingClass) {
        super(dataList, bindingClass);
        mContext = context;
    }


    @Override
    protected void bindData(ItemControllerAutoBinding binding, Relay device) {
        TransitionManager.beginDelayedTransition(binding.layoutRoot, new Fade());
        if ("未配置".equals(device.getName())) {
            binding.cardNo.setVisibility(View.VISIBLE);
            binding.cardYes.setVisibility(View.GONE);
            return;
        } else {
            binding.cardNo.setVisibility(View.GONE);
            binding.cardYes.setVisibility(View.VISIBLE);
        }
        if (device.getName().equals(RoomController.fan.getName())) {
            binding.tvInfo.setText(GasSensor.getQualityAir());
            binding.tvInfo.setTextColor(GasSensor.getQualityAirColor());
        } else {
            binding.tvInfo.setText(null);
        }
        changeState(binding, device);
        binding.tvController.setText(device.getName());
        if (AutoModelSet.isAutoHumidity() && RoomController.DEVICE_NAME[2].equals(device.getName())//加湿器
                || AutoModelSet.isAutoHumidity() && RoomController.DEVICE_NAME[16].equals(device.getName())  //除湿器
                || AutoModelSet.isAutoVentilator() && RoomController.DEVICE_NAME[12].equals(device.getName())  //换气扇
                || AutoModelSet.isAutoEven() && RoomController.DEVICE_NAME[7].equals(device.getName()) //匀风扇
                || AutoModelSet.isAutoDisinfect() && RoomController.DEVICE_NAME[8].equals(device.getName())  //消毒灯
                || !AutoModelSet.getAirExchangeMode().equals(SpinnerList.AIR_EXCHANGE_MODES[0]) && RoomController.DEVICE_NAME[13].equals(device.getName()) //新风
        ) {
            binding.cardController.setOnClickListener(v -> Toasty.info(mContext, "该设备由自动控制系统接管中").show());
        } else {
            binding.cardController.setOnClickListener(view -> {
                DialogUtil.showLoadingDialog(mContext, mContext.getString(R.string.in_operate));
                MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Result>() {
                    @Override
                    public Result doInQueueThread() {
                        Result result = new Result();
                        result.setOperateResult(device.setPowerSupply(!device.isPowerSupply()));
                        result.setState(device.isPowerSupply());
                        return result;
                    }

                    @Override
                    public void doInUIThread(Result result) {
                        if (result.isOperateResult()) {
                            changeState(binding, device);
                            Toasty.success(mContext, mContext.getString(R.string.operate_success)).show();
                            UserLog.operate("手动：" + (result.isState() ? "开启" : "关闭") + device.getName());
                        } else {
                            Toasty.error(mContext, mContext.getString(R.string.operate_fail)).show();
                            UserLog.operateError("手动操作失败：" + (result.isState() ? "开启" : "关闭") + device.getName());
                        }
                        DialogUtil.hideLoadingDialog();
                    }
                });
            });
        }
    }

    private void changeState(ItemControllerAutoBinding binding, Relay device) {
        if (device.isPowerSupply()) {
            binding.tvState.setText("运行中");
            binding.ivController.setImageResource(device.getIconOpen());
            binding.ivPower.setBackground(mContext.getDrawable(R.drawable.bg_controller_open));
            binding.ivPower.setImageDrawable(mContext.getDrawable(R.mipmap.switch_on));
            binding.cardController.setBackgroundColor(Color.parseColor("#00BDF4"));
            binding.ivController.setImageDrawable(mContext.getDrawable(device.getIconOpen()));
            binding.tvState.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvController.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvPower.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            // 地暖在超过最大温度限制后会自动断电，此时状态显示为“高温保护”而非“未启动”
            if(device.getName().equals(RoomSetting.getFloorName()) && RoomSensor.getFloorTemperature() > AutoModelSet.getAutoFlorMaxTemp()) {
                binding.tvState.setText("高温保护中");
            } else {
                binding.tvState.setText("未启动");
            }
            binding.ivController.setImageResource(device.getIconClose());
            binding.cardController.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33DCE3E3" : "#F2F0F1"));
            binding.ivPower.setBackground(mContext.getDrawable(R.drawable.bg_controller_close));
            binding.ivPower.setImageDrawable(mContext.getDrawable(R.mipmap.switch_off));
            binding.ivController.setImageDrawable(mContext.getDrawable(device.getIconClose()));
            binding.tvState.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvController.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvPower.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
        }
        binding.tvPower.setVisibility(RoomController.relay.getModel().equals(RoomController.relay.getModels()[2]) ? View.VISIBLE : View.GONE);
        binding.tvPower.setText("实时功率：" + device.getPower() + "w");
    }
}
