package com.example.iot_controlhost.utils.database;

import com.blankj.utilcode.util.StringUtils;
import com.example.iot_controlhost.MyApp;
import com.example.iot_controlhost.model.EnergyRecord;
import com.example.iot_controlhost.model.EnergyRecordDao;
import com.example.iot_controlhost.model.Log;
import com.example.iot_controlhost.model.LogDao;
import com.example.iot_controlhost.model.sensor.ConsumptionSensor;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.log.UserLog;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EnergyDBManager {
    /**
     * 操作类
     */
    private static EnergyRecordDao energyDao = MyApp.getDaoSession().getEnergyRecordDao();

    private static ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * 增加
     */
    public static void insert(EnergyRecord energyRecord) {
        executor.execute(() -> energyDao.insert(energyRecord));
    }


    /**
     * 删除
     */
    public static void remove(Long id) {
        energyDao.deleteByKey(id);
    }

    public static Double queryMaxDate() {
        QueryBuilder<EnergyRecord> qb = energyDao.queryBuilder();
        List<EnergyRecord> data = qb.orderDesc(EnergyRecordDao.Properties.Datetime).limit(10).list();
        if (!data.isEmpty()) {
            if(data.get(0).getEnergy() == 0) {
                MyLog.test("!!!queryMaxDate: data is empty: " + data.size());
                return 0.0;
            }
            return data.get(0).getEnergy();
        }
        MyLog.test("queryMaxDate: data is empty: " + data.size());
        return 0.0;
    }
    public static Double queryDateRange(Long startDate, Long endDate) {
        List<EnergyRecord> data = energyDao.queryBuilder()
                .where(EnergyRecordDao.Properties.Datetime.between(new Date(startDate), new Date(endDate)))
                .orderAsc(EnergyRecordDao.Properties.Datetime)
                .list();

        if (data.isEmpty()) return 0.0;

        double earliestValue = data.get(0).getEnergy();
        double latestValue = data.get(data.size() - 1).getEnergy();
        double result = latestValue - earliestValue;
        return result < 0 ? 0.0 : result;
    }

    /**
     * 获取最后记录能耗的时间
     */
    public static Date queryLastRecordDate() {
        QueryBuilder<EnergyRecord> qb = energyDao.queryBuilder();
        List<EnergyRecord> data = qb.orderDesc(EnergyRecordDao.Properties.Datetime).limit(1).list();
        if (!data.isEmpty()) {
            return data.get(0).getDatetime();
        }
        return null;
    }

    /**
     * 删除2个月前的日志
     */
    public static void clearLogsOlderThanThreeMonths() {
        RxJavaUtils.doInIOThread(new RxIOTask<Object>(null) {
            @Override
            public Void doInIOThread(Object o) {
                try {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.MONTH, -2);
                    Date threeMonthsAgo = calendar.getTime();
                    energyDao.queryBuilder()
                            .where(LogDao.Properties.Datetime.lt(threeMonthsAgo))
                            .buildDelete()
                            .executeDeleteWithoutDetachingEntities();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

}
