import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';

class LvRecord {
    @prop({ required: true })
    lv: number;
    @prop({ required: true })
    apBefore: number;
    @prop({ required: true })
    ap: number;
}

/**
  * 体力系统 
*/
@index({ roleId: 1 })

export default class ActionPoint extends BaseModel {
    @prop({ required: true })
    roleId: string;					// 角色 id

    @prop({ required: true })
    refTime: number;                // 刷新时间，时间戳
    @prop({ required: true })
    ap: number;                     // 当前体力
    @prop({ required: true })
    apBefore: number;                     // 变化之前体力

    @prop({ required: true })
    buyRefTime: number;             // 购买刷新时间，时间戳
    @prop({ required: true })
    buyTimes: number;                     // 当前体力

    @prop({ required: true, type: LvRecord, _id: false })
    lvRecords: LvRecord[];                     // 当前体力

    public static async getAp(roleId: string, lean = true) {
        let result: ActionPointType = await ActionPointModel.findOne({roleId}).select('ap refTime buyRefTime buyTimes apBefore lvRecords').lean(lean);
        if(!result) {
            result = await ActionPointModel.findOneAndUpdate({roleId}, { $setOnInsert: { ap: 0, refTime: 0, buyRefTime: 0, buyTimes: 0 } }, {new: true, upsert: true}).lean(lean)
        }
        return result;
    }
  
    public static async saveAp(roleId: string, ap: number, apBefore: number, refTime: number, lean = true) {
        let result: ActionPointType = await ActionPointModel.findOneAndUpdate({roleId}, { $set: {ap, refTime, apBefore }, $setOnInsert: {buyRefTime: 0, buyTimes: 0} }, {upsert: true, new: true}).lean(lean);
        return result;
    }

    public static async setLvRecord(roleId: string, lv: number, ap: number, apBefore: number) {
        let result: ActionPointType = await ActionPointModel.findOneAndUpdate({ roleId }, { $push: {lvRecords: { lv, ap, apBefore }}}, {new: true}).lean();
        return result;
    }

    public static async saveBuyTimes(roleId: string, buyTimes: number, buyRefTime: number) {
        let result: ActionPointType = await ActionPointModel.findOneAndUpdate({ roleId }, { $set: {buyTimes, buyRefTime}, $setOnInsert: { ap: 0, refTime: 0 } }, {upsert: true, new: true}).lean();
        return result;
    }

    public static async resetBuyTimes(roleId: string) {
        let result: ActionPointType = await ActionPointModel.findOneAndUpdate({ roleId }, { $set: { buyRefTime: 0 } }).lean();
        return result;
    }

    public static async deleteAccount(roleId: string) {
        let result = await ActionPointModel.deleteMany({roleId});
        return result;
    }
}

export const ActionPointModel = getModelForClass(ActionPoint);

export interface ActionPointType extends Pick<DocumentType<ActionPoint>, keyof ActionPoint>{}