import { Application, BackendSession } from 'pinus';
import { DailyRecordModel } from '../../../db/DailyRecord';
import { STATUS } from '../../../consts/statusCode';
import { resResult } from '../../../pubUtils/util';
import { RoleModel } from '../../../db/Role';
import { getDailyNum, getDailyBattleList, getDailyBuyCountCost } from '../../../services/dailyBattleService';
import { getGoldObject, handleCost } from '../../../services/role/rewardService';
import { gameData } from '../../../pubUtils/data';
import { DEBUG_MAGIC_WORD, ITEM_CHANGE_REASON } from '../../../consts';

export default function(app: Application) {
    return new DailyBattleHandler(app);
}

export class DailyBattleHandler {
    constructor(private app: Application) {
    }

    // 获取关卡列表
    async getData(msg: { }, session: BackendSession) {
        let roleId = session.get('roleId');

        let role = await RoleModel.findByRoleId(roleId); 
        let result = await getDailyBattleList(role);

        return resResult(STATUS.SUCCESS, { list: result });
    }

    // 购买每日次数
    async buyNum(msg: { type: number, count: number }, session: BackendSession) {
        let {type, count} = msg;
        if( !count || count < 0) return resResult(STATUS.WRONG_PARMS);
        const roleId = session.get('roleId');
        const sid = session.get('sid');

        const curDaily = gameData.daily.find(cur => cur.dailyType == type);
        if(!curDaily) return resResult(STATUS.DAILY_TYPE_NOT_FOUND);

        let { buyCount = 0 } = await DailyRecordModel.refreshRecord(roleId, type);

        if(buyCount + count > curDaily.timesCanBuy ) {
            return resResult(STATUS.DAILY_REFRESH_TIMES_LACK)
        }
        let buyCost = 0;
        for(let i = 1; i <= count; i++) {
            let num = buyCount + i;
            buyCost += getDailyBuyCountCost(num);
        }
        let role = await RoleModel.findByRoleId(roleId);
        if(buyCost > role.gold) {
            return resResult(STATUS.DAILY_REFRESH_GOLD_LACK);
        }

        await handleCost(roleId, sid, [getGoldObject(buyCost)], ITEM_CHANGE_REASON.DAILY_BATTLE_BUY_CNT);
        let newDailyRecord = await DailyRecordModel.increseBuyCount(roleId, type, count);

        let checkDailyResult = await getDailyNum(newDailyRecord, role);
        return resResult(STATUS.SUCCESS, { type, ...checkDailyResult, buyCost});
    }

    async debugResetNum(msg: { magicWord: string, type: number }, session: BackendSession) {
        const { magicWord, type } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let roleId = session.get('roleId');
        await DailyRecordModel.deleteAccount(roleId);
        return resResult(STATUS.SUCCESS);
    }
}