import moment = require("moment");
import { pinus } from "pinus";
import { ADDICTION_PREVENTION_CODE, ADULT_AGE, GUEST_MAX_TIME, PUSH_ROUTE, STATUS } from "../consts";
import { UserModel, UserType } from "../db/User";
import { getAge } from "../pubUtils/timeUtil";
import { resResult } from "../pubUtils/util";
import { incOnlineTime, setOnlineTime } from "./redisService";
import { checkTeeanAgerTime } from '../pubUtils/authenticateUtil';
import { sendMessageToUserWithSuc } from "./pushService";

export async function reportOneOnline(roleId: string, userCode: string, sid: string, isLogin: boolean = false, user?: UserType) {
    if (!user) user = await UserModel.findUserByUserCode(userCode);
    if (!user) return false;

    let sumTime = await incOnlineTime(userCode, false, 5 * 60); // 返回单位为分
    let todaySumTime = await incOnlineTime(userCode, true, 5 * 60);
    
    let { isGuest, hasAuthenticated, birthday } = user;
    let age = getAge(birthday);
    let isAdult = age >= ADULT_AGE;

    if (isGuest || !hasAuthenticated) {
        if (sumTime > GUEST_MAX_TIME) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest,
                guestTime: sumTime,                     // 游客已体验时间
                hasAuthenticated,                       // 是否进行过实名认证
                isAdult,                         // 是否已成年
                todayPlayTime: todaySumTime,            // 今天已游戏时长
                type: ADDICTION_PREVENTION_CODE.GUEST,
            }, sid);
        }
    } else {
        let code = checkTeeanAgerTime(isAdult, todaySumTime);
        if(code != ADDICTION_PREVENTION_CODE.SUCCESS) {
            sendMessageToUserWithSuc(roleId, PUSH_ROUTE.PLAY_TIME, {
                isGuest,
                guestTime: 0,                           // 游客已体验时间
                hasAuthenticated,                       // 是否进行过实名认证
                isAdult,                                // 是否已成年
                todayPlayTime: todaySumTime,            // 今天已游戏时长
                type: code
            }, sid);
        }
    }
}

export async function savePlayTime(userCode: string, user?: UserType) {
    if (!user) user = await UserModel.findUserByUserCode(userCode);
    if (!user) return false;

    let time = Date.now() - user.lastLoginTime.getTime();
    let setsumTime = (user.playTime||0) + Math.floor(time/1000);
    let settodaySumTime = (user.todayPlayTime||0) + Math.floor(time/1000);

    let sumTime = await setOnlineTime(userCode, false, setsumTime); // 返回单位为分
    let todaySumTime = await setOnlineTime(userCode, true, settodaySumTime);

    let { isGuest, hasAuthenticated } = user;
    await UserModel.updatePlayTime(userCode, isGuest || !hasAuthenticated, settodaySumTime, setsumTime);
}