package com.example.iot_controlhost.utils.database;


import com.bbitcn.sericulture.base.BaseTempDataBase;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.MyApp;
import com.example.iot_controlhost.model.Silkworm;
import com.example.iot_controlhost.model.SilkwormDao;
import com.example.iot_controlhost.model.SilkwormNew;
import com.example.iot_controlhost.utils.DateUtils;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.log.MyLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.query.QueryBuilder;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

public class SilkwormDBManager extends BaseTempDataBase<SilkwormNew> {

    public static SilkwormDBManager INSTANCE = new SilkwormDBManager();

    @Override
    public @NotNull String getKey() {
        return "SILKWORM_TEMP_DB";
    }

    @Override
    public SilkwormNew defaultData() {
        return new SilkwormNew();
    }

    @Override
    public @NotNull Type getType() {
        return new TypeToken<SilkwormNew>() {
        }.getType();
    }


    public static final String SILKWORM_TEMP_DB_IS_INIT = "SILKWORM_TEMP_DB_IS_INIT";


    public static void initSK() {
        if (MMKVUtil.get(SILKWORM_TEMP_DB_IS_INIT, false)) {
            return;
        }
        QueryBuilder<Silkworm> qb =  MyApp.getDaoSession().getSilkwormDao().queryBuilder();
        qb.orderDesc(SilkwormDao.Properties.Id);
        qb.limit(1);
        Silkworm old = qb.unique();
        if (old != null && old.getEndDate() == null) {
            // 如果数据库有数据，则迁移到现在的临时数据库
            INSTANCE.init(new SilkwormNew(MMKVUtil.get("CULTIVATE_CODE"), old.getName(), old.getStartDate(), old.getEndDate(), old.getNumber(), old.getVariety()));
        }
        MMKVUtil.put(SILKWORM_TEMP_DB_IS_INIT, true);
    }


    //---------------------------------------------------

    public static SilkwormNew getLatestSilkworm() {
        return INSTANCE.getData();
    }

    /**
     * 当前是否是共育
     */
    public static boolean isStarting() {
        SilkwormNew silkworm = INSTANCE.getData();
        // kotlin不会返回null，所以这里不能判断silkworm ！=null  而是要用 silkworm.getId()!=null
        if (silkworm.getId() != null && silkworm.getEndDate() == null) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前共育第几天
     */
    public static int getStartToNowDays() {
        if (isStarting()) {
            return DateUtils.daysFromTodayInclusive(getLatestSilkworm().getStartDate());
        } else {
            return -1;
        }
    }

    /**
     * 改
     */
    public static void updateCurDate() {
        SilkwormNew silkwormNew = INSTANCE.getData();
        silkwormNew.setEndDate(new Date());
        INSTANCE.init(silkwormNew);
    }

}
