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.Controller;
import com.example.iot_controlhost.model.controller.Dehumidifier485;
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.ui.dialog.Dehumidifier485Dialog;
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;

/**
 * 自动页面控制设备列表。
 */
public class AutoControllerAdapter extends BaseRecyclerAdapter<Controller, ItemControllerAutoBinding> {
    Context mContext;

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

    @Override
    protected void bindData(ItemControllerAutoBinding binding, Controller 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(getDisplayName(device));
        if (isAutoControlled(device)) {
            binding.cardController.setOnClickListener(v -> Toasty.info(mContext, "该设备由自动控制系统接管中").show());
        } else {
            binding.cardController.setOnClickListener(view -> {
                if (device instanceof Dehumidifier485) {
                    new Dehumidifier485Dialog(mContext, (Dehumidifier485) device).show();
                    return;
                }
                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 boolean isAutoControlled(Controller device) {
        return AutoModelSet.isAutoHumidity() && RoomController.DEVICE_NAME[2].equals(device.getName())
                || AutoModelSet.isAutoHumidity() && RoomController.DEVICE_NAME[16].equals(device.getName())
                || AutoModelSet.isAutoHumidity() && device instanceof Dehumidifier485
                || 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());
    }

    private void changeState(ItemControllerAutoBinding binding, Controller device) {
        if (device.isPowerSupply()) {
            binding.tvState.setText("运行中");
            binding.ivController.setImageResource(getIconOpen(device));
            binding.ivPower.setBackground(mContext.getDrawable(R.drawable.bg_controller_open));
            binding.ivPower.setImageDrawable(mContext.getDrawable(R.mipmap.switch_on));
            binding.cardController.setBackgroundColor(getOpenColor(device));
            binding.ivController.setImageDrawable(mContext.getDrawable(getIconOpen(device)));
            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(getIconClose(device));
            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(getIconClose(device)));
            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"));
        }
        if (device instanceof Dehumidifier485 && RoomController.relay.getModel().equals(RoomController.relay.getModels()[2])) {
            binding.tvPower.setVisibility(View.VISIBLE);
            binding.tvPower.setText("实时功率：" + RoomController.dehumidifier485Relay.getPowerText() + "w");
        } else if (device instanceof Relay && RoomController.relay.getModel().equals(RoomController.relay.getModels()[2])) {
            binding.tvPower.setVisibility(View.VISIBLE);
            binding.tvPower.setText("实时功率：" + ((Relay) device).getPowerText() + "w");
        } else {
            binding.tvPower.setVisibility(View.GONE);
        }
    }

    private int getIconOpen(Controller device) {
        if (device instanceof Relay) {
            return ((Relay) device).getIconOpen();
        }
        if (device instanceof Dehumidifier485) {
            return R.mipmap.ven_open;
        }
        return R.mipmap.open;
    }

    private int getIconClose(Controller device) {
        if (device instanceof Relay) {
            return ((Relay) device).getIconClose();
        }
        if (device instanceof Dehumidifier485) {
            return R.mipmap.ven_close;
        }
        return R.mipmap.close;
    }

    private int getOpenColor(Controller device) {
        if (device instanceof Dehumidifier485) {
            return Color.parseColor("#00A1FF");
        }
        return Color.parseColor("#00BDF4");
    }

    private String getDisplayName(Controller device) {
        if (device instanceof Dehumidifier485) {
            return ((Dehumidifier485) device).getDisplayName();
        }
        return device.getName();
    }
}
