import { FrontendOrBackendSession, pinus } from "pinus";
import { STATUS } from '../consts/statusCode';
import { resResult, shouldRefresh, shouldRefreshWeek } from '../pubUtils/util';
import { nowSeconds } from "../pubUtils/timeUtil";
// import { RoleModel } from '../db/Role';
import { refDailyTask, refDailyTaskBox } from './taskService'

/**
 * 刷新
 * @param session 
 */
export async function refresh(session: FrontendOrBackendSession) {
    const roleId = session.get('roleId');
    const sid = session.get('sid');
    let uids = [{uid: roleId, sid}];
    pinus.app.get('channelService').pushMessageByUids('onPushCurrentTime', resResult(STATUS.SUCCESS, {time: Date.now()}), uids);
    await refreshDaily(session);
}

/**
 * 每日刷新
 * @param session 
 */
export async function refreshDaily(session: FrontendOrBackendSession) {

    if(session.get('roleId')) {
        let refDaily: number = session.get('refDaily');   // 10位时间戳，每天每人更新一次
        let refWeekly: number = session.get('refWeekly');   // 10位时间戳，每天每人更新一次
        if(!refDaily || shouldRefresh(new Date(refDaily * 1000), new Date())) {
            refDaily = nowSeconds();
            session.set('refDaily', refDaily);
            session.push('refDaily', () => {});
            await refDailyTask(session.get('roleId'), session.get('sid'));
        }
    
        if(!refWeekly || shouldRefreshWeek(new Date(refWeekly * 1000), new Date())) {
            refWeekly = nowSeconds();
            session.set('refWeekly', refWeekly);
            session.push('refWeekly', () => {});
            await refDailyTaskBox(session.get('roleId'), session.get('sid'));
        }
    }
}