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'
// import { EVENT_STATUS, FUNCS_ID } from "../consts";
// import { startEvent } from "./eventSercive";
import * as dicParam from '../pubUtils/dicParam';
import { dispatch } from "../pubUtils/dispatcher";

/**
 * 刷新
 * @param session 
 */
export async function refresh(session: FrontendOrBackendSession) {
    const roleId = session.get('roleId')||'test';
    const sid = session.get('sid');

    let uids = [{uid: roleId, sid}];
    if(dicParam.SERVER_DEBUG_MODE.CURRENT_TIME != 1) {
        pinus.app.get('channelService').pushMessageByUids('onPushCurrentTime', resResult(STATUS.SUCCESS, {time: Date.now()}), uids);
    } else {
        let guilds = pinus.app.getServersByType('guild');
        let guild = dispatch(roleId, guilds, 'guild');
        let currentTime = await pinus.app.rpc.guild.guildActivityRemote.getCurrentTime.toServer(guild.id);
        pinus.app.get('channelService').pushMessageByUids('onPushCurrentTime', resResult(STATUS.SUCCESS, {time: currentTime }), uids);
    }
    await refreshDaily(session);
    // await startEvent(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'));
        }
    }
}