package com.example.iot_controlhost.model.sensor;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.base.SetAddress;
import com.example.iot_controlhost.model.Device;
import com.example.iot_controlhost.model.ParameterizedTypeImpl;
import com.example.iot_controlhost.model.thread.QueueIOTask;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.Variable;
import com.example.iot_controlhost.utils.log.MyLog;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android_serialport_api.SerialPortUtil;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
/**
 * 传感器父类
 */
public abstract class Sensor extends Device implements SetAddress {

    /**
     * 上次采集时间
     * 为0时为开机时初始化的值
     */
    private long lastRecordTime;
    /**
     * 记录采集的值
     */
    protected final String HISTORY_VALUE = name + "HISTORY_VALUE";
    protected static SerialPortUtil serialPortUtil;

    public Sensor(String name) {
        super(name);
        serialPortUtil = SerialPortUtil.getInstance(SerialPortUtil.TYPE_SENSOR);
        lastRecordTime = 0;
    }

    /**
     * 采集所有数据，子类需要重写
     * 指令+解析方式+赋予数据给自身变量
     *
     * @param model   型号
     * @param address 地址
     * @return 是否解析成功
     */
    public abstract boolean collectSensorData(String model, String address);

    /**
     * 增加历史记录
     * ！！！！存在内存泄漏风险！！！！！
     */
//    private void addHistoryData() {
//        MyLog.sensor(name + "记录历史值");
//        List temp = getHistoryData();
//        temp.add(this);
//        setLastRecordTime(System.currentTimeMillis());
//        MMKVUtil.put(HISTORY_VALUE, GsonUtils.toJson(temp));
//    }

    /**
     * 获得该传感器的所有历史记录
     *
     * @param <T> 要转变的Sensor子类，方便后续直接调用方法，需要List<CO2Sensor> s = sensor.getHistoryJson();先获取再foreach
     * @return
     */
//    public <T> List<T> getHistoryData() {
//        Type type = new ParameterizedTypeImpl(getClass());
//        List<T> list = new Gson().fromJson(MMKVUtil.get(HISTORY_VALUE, "[]"), type);
//        return list;
//    }

    /**
     * 清理过去历史数据
     */
//    public int clearHistoryData() {
//        int count = 0;
//        List temp = getHistoryData();
//        int size = temp.size();
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DAY_OF_YEAR, -30);
//        long time = calendar.getTimeInMillis();
////        MyLog.test("当前时间: " + new Date(System.currentTimeMillis()) + ", 30天前时间戳: " + new Date(time));
//
//        Iterator it = temp.iterator();
//        while (it.hasNext()) {
//            Sensor sensor = (Sensor) it.next();
//            if (sensor.getLastRecordTime() < time) {
//                it.remove();
//                count++;
//            }
//        }
//        MMKVUtil.put(HISTORY_VALUE, GsonUtils.toJson(temp));
////        MyLog.test(getName() + "历史数据总条数: " + size + "，现删除: " + count + "条历史数据");
//        return count;
//    }

    /**
     * 刷新传感器所有数据
     */
    final public void getAllSensorData() {
        if (isAvailable()) {
            if (this instanceof ConsumptionSensor && RoomController.relay.getModel().equals(RoomController.relay.getModels()[2])) {
                //能耗传感器 && 继电器为BBIT-H-v1.0型   需要使用控制器的串口
                MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> getSensorData()));
            } else {
                MyQueue.getInstance(MyQueue.TYPE_SENSOR).addTask(new QueueIOTask(() -> getSensorData()));
            }
        }
    }

    /**
     * 获取传感器数据
     * 具体方法
     */
    private void getSensorData() {
        MyLog.sensor(name + "采集数据");
        boolean result;
        try {
            // 等待500ms后读取，防止与上次读取冲突
            Thread.sleep(500);
            result = collectSensorData(getModel(), getAddress());
        } catch (Exception e) {
            result = false;
        }
        if (result) {
            //解析成功
//            if (System.currentTimeMillis() - getLastRecordTime() > Variable.SENSOR_RECORD_TIME) {
//                addHistoryData();
//            }
        } else {
            MyLog.sensorError("传感器：" + name + "数据解析失败");
        }
    }

    public long getLastRecordTime() {
        return lastRecordTime;
    }

    public void setLastRecordTime(long lastRecordTime) {
        this.lastRecordTime = lastRecordTime;
    }

    /**
     * 子类需要重写来输出传感器详细信息
     */
    @Override
    public abstract String toString();


    @Override
    public boolean test(String deviceModel, String deviceAddress) {
        return collectSensorData(deviceModel, deviceAddress);
    }

    @Override
    public String getTestState() {
        return toString();
    }

    /**
     * 获取硬件基础信息
     * 使用父类方法
     */
    public String getBaseInfo() {
        return super.toString();
    }

    @Override
    public int addFailTimes() {
        return super.addFailTimes();
    }


}
