import { FrontendOrBackendSession, pinus } from "pinus";
import { shouldRefresh, shouldRefreshWeek } from '../pubUtils/util';
import { nowSeconds } from "../pubUtils/timeUtil";
import { refDailyTask, refDailyTaskBox } from './task/taskService'
import { dispatch } from "../pubUtils/dispatcher";
import { sendMessageToUserWithSuc } from "./pushService";
import { PUSH_ROUTE } from "../consts";
import { isDebugTime } from "../pubUtils/sdkUtil";

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

    if(!isDebugTime()) {
        sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PUSH_CURRENT_TIME, { time: Date.now() }, sid);
    } 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);
        sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PUSH_CURRENT_TIME, { time: currentTime }, sid);
    }
    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'));
        }
    }
}