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

@index({ id: 1 })
@index({ seasonNum: 1 })
export default class PVPConfig extends BaseModel {

    @prop({ required: true, default: 1 })
    seasonNum: number;              // 赛季

    @prop({ required: true })
    seasonStartTime: number;         // 赛季开始时间

    @prop({ required: true })
    seasonRewardTime: number;         // 结算奖励时间

    @prop({ required: true })
    seasonEndTime: number;         // 赛季结束的时间

    @prop({ required: true })
    hasSettleReward: boolean;         // 赛季结束的时间

    
    public static async findCurPVPConfig() {
        let seasonNum = await CounterModel.getCounter(COUNTER.PVP_SEASON_NUM);
        const result: PVPConfigType = await PVPConfigModel.findOne({ seasonNum }).lean(true);
        return result;
    }

    public static async findPVPConfig(seasonNum: number) {
        const result: PVPConfigType = await PVPConfigModel.findOne({ seasonNum }).lean(true);
        return result;
    }

    public static async createPVPConfig(seasonNum: number, seasonStartTime: number, seasonRewardTime: number, seasonEndTime: number) {
        const result: PVPConfigType = await PVPConfigModel.findOneAndUpdate({ seasonNum }, { seasonStartTime, seasonRewardTime, seasonEndTime, hasSettleReward: false }, { upsert: true, new: true }).lean(true);
        return result;
    }

    public static async setReward(seasonNum: number) {
        const result: PVPConfigType = await PVPConfigModel.findOneAndUpdate({ seasonNum }, { hasSettleReward: true }, { new: true }).lean(true);
        return result;
    }

    public static async setCurPvpConfig(update: PVPConfigUpdate) {
        let seasonNum = await CounterModel.getCounter(COUNTER.PVP_SEASON_NUM);
        const result: PVPConfigType = await PVPConfigModel.findOneAndUpdate({ seasonNum }, update).lean(true);
        return result;
    }
}

export const PVPConfigModel = getModelForClass(PVPConfig);

export interface PVPConfigType extends Pick<DocumentType<PVPConfig>, keyof PVPConfig> {
    id: number;
};
export type PVPConfigUpdate = Partial<PVPConfigType>; // 将所有字段变成可选项
