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

@index({ configId: -1 })
export default class GVGConfig extends BaseModel {

    @prop({ required: true, default: 1 })    
    configId: number;       // 配置唯一id

    @prop({ required: true }) 
    teamTime: number;    // 组建期开始

    @prop({ required: true }) 
    prepareTime: number; // 准备期开始

    @prop({ required: true }) 
    battleTime: number;  // 激战期开始

    @prop({ required: true }) 
    scheduleTime: number;  // 下次定时任务时间

    public static async createNewConfig(teamTime: number, prepareTime: number, battleTime: number, scheduleTime: number) {
        const configId = await CounterModel.getNewCounter(COUNTER.GVG_CONFIG);
        const result: GVGConfigType = await GVGConfigModel.findOneAndUpdate({ configId }, { $set: { teamTime, prepareTime, battleTime, scheduleTime } }, { upsert: true, new: true }).lean();
        return result;
    }

    public static async findConfig() {
        let configId = await CounterModel.getCounter(COUNTER.GVG_CONFIG);
        const result: GVGConfigType = await GVGConfigModel.findOne({ configId  }, { _id: 0 }).lean();
        return result;
    }

    public static async updateConfig(configId: number, teamTime: number, prepareTime: number, battleTime: number, scheduleTime: number) {
        const result: GVGConfigType = await GVGConfigModel.findOneAndUpdate({ configId }, { $set: { teamTime, prepareTime, battleTime, scheduleTime } }, { new: true }).lean();
        return result;
    }

}

export const GVGConfigModel = getModelForClass(GVGConfig);

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