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.Log;
import com.example.iot_controlhost.model.LogDao;
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 LogDBManager {

    private static ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * 增加
     */
    public static void insertLog(Log log) {
        executor.execute(() -> logDao.insert(log));
    }

    /**
     * 每页的长度
     */
    private static int pageSize = 20;
    /**
     * 日志操作类
     */
    private static LogDao logDao = MyApp.getDaoSession().getLogDao();

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

    public static void removeAll() {
        logDao.deleteAll();
    }

    public static List<Log> queryDateRange(Date startDate, Date endDate) {
        QueryBuilder<Log> qb = logDao.queryBuilder();
        // 创建日期区间查询条件
        WhereCondition dateCondition = LogDao.Properties.Datetime.between(startDate, endDate);
        QueryBuilder<Log> dateRangeQueryBuilder = qb.where(dateCondition);
        return dateRangeQueryBuilder.list();
    }


    /**
     * 返回某类型的所有日志
     *
     * @param tagType MyLog类下的TAG常量 为空时返回全部
     */
    public static List<Log> queryList(String tagType, int currentPage) {
        QueryBuilder<Log> qb = logDao.queryBuilder();
        if (!StringUtils.isEmpty(tagType)) {
            qb.where(LogDao.Properties.Tag.like("%" + tagType + "%"));
        }else{
            qb.whereOr(
                    LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_OPERATE + "%"),
                    LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_SENSOR + "%"),
                    LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_TASK + "%"),
                    LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_SYSTEM + "%")
            );
        }
        return qb.offset((currentPage - 1) * pageSize)
                .limit(pageSize)
                .orderDesc(LogDao.Properties.Datetime)
                .list();
    }

    /**
     * 返回某类型的所有日志
     */
    public static List<Log> queryAllList() {
        QueryBuilder<Log> qb = logDao.queryBuilder();
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        Date oneWeekAgo = calendar.getTime();
        return qb.orderDesc(LogDao.Properties.Datetime)
                .where(LogDao.Properties.Datetime.between(oneWeekAgo, currentDate))
                .whereOr(
                        LogDao.Properties.Tag.like("%" + MyLog.TAG_APP + "%"),
                        LogDao.Properties.Tag.like("%" + MyLog.TAG_NETWORK + "%")
                )
                .list();
    }

    public static List<Log> queryWorkLogs(int currentPage) {
        return logDao.queryBuilder()
                .orderDesc(LogDao.Properties.Datetime)
                .whereOr(
                        LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_OPERATE + "%"),
                        LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_SENSOR + "%"),
                        LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_TASK + "%"),
                        LogDao.Properties.Tag.like("%" + UserLog.TAG_USER_SYSTEM + "%")
                )
                .offset((currentPage - 1) * pageSize)
                .limit(pageSize)
                .list();
    }

    /**
     * 改
     */
    public static void update(Log log) {
        logDao.update(log);
    }

    /**
     * 删除1个月前的日志
     */
    public static void clearLogsOlderThanOneMonthsSync() {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -1);
            Date oneMonthAgo = calendar.getTime();

            logDao.queryBuilder()
                    .where(LogDao.Properties.Datetime.lt(oneMonthAgo))
                    .buildDelete()
                    .executeDeleteWithoutDetachingEntities();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
