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

@index({ id: 1 })
export default class SystemConfig extends BaseModel {
    @prop({ required: true, default: 1})
    id: number;	
    @prop({ required: true })
    warId: number;					// 地图
    @prop({ required: true, default: 1 })
    seasonNum: number;              // 赛季
    @prop({ required: true })
    seasonEndTime: number;         //赛季结束的时间
    @prop({ required: true , default: 0 })
    oldSeasonEndTime: number;         //上赛季结束的时间
    @prop({ required: false })
    settleGuildWeeklyTime: number;

    public static async findSystemConfig(lean = true) {
        const result: SystemConfigType = await SystemConfigModel.findOne({}).lean(lean);
        return result;
    }

    public static async createSystemConfig(seasonEndTime: number, warId: number, lean = true) {
        const result: SystemConfigType = await SystemConfigModel.findOneAndUpdate({}, { seasonEndTime, warId, seasonNum: 1 }, { upsert: true, new: true }).lean(lean);
        return result;
    }

    public static async updateSystemConfig(update: { seasonEndTime?: number, warId?: number, seasonNum?:number , oldSeasonEndTime?: number, settleGuildWeeklyTime?: number}, lean = true) {
        const result: SystemConfigType = await SystemConfigModel.findOneAndUpdate({}, update, { upsert: true, new: true }).lean(lean);
        return result;
    }

    public static async updateSeason( seasonEndTime: number, oldSeasonEndTime: number, lean = true) {
        const result: SystemConfigType = await SystemConfigModel.findOneAndUpdate({},  { seasonEndTime, $inc: { seasonNum: 1 }, oldSeasonEndTime }, { upsert: true, new: true }).lean(lean);
        return result;
    }
}

export const SystemConfigModel = getModelForClass(SystemConfig);

export interface SystemConfigType extends Pick<DocumentType<SystemConfig>, keyof SystemConfig> { 
    id: number;
};