import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { Reward, HeroReward, HeroScore } from '../domain/battleField/pvp';

@index({ roleId: 1, seasonNum: 1 })
export default class PvpSeasonResult extends BaseModel {
    
    @prop({ required: true })
    roleId: string;

    @prop({ required: true })
    seasonNum: number;
    
    @prop({ required: true })
    seasonEndTime: number;

    @prop({ required: true })
    score: number;

    @prop({ required: true, type: () => HeroScore, default:[] })
    heroScores: HeroScore[];

    @prop({ required: true })
    rankLv: number;
    
    @prop({ required: true,  default: true })
    show: boolean;

    @prop({ required: true, type: () => HeroReward, default: [], _id: false})
    heroGoods: HeroReward[];

    @prop({ required: true, type: Reward, default: [], _id: false})
    rankGoods: Reward[];

    @prop({ required: true })
    newScore: number;

    @prop({ required: true, type: () => HeroScore, default:[] })
    newHeroScores: HeroScore[];

    @prop({ required: true, type: Number, default: [] })
    receivedBox: Array<number>;

    @prop({ required: true, default: 0 })
    seasonWinNum: number;          // 本赛季胜利次数

    public static async updatePvpSeasonResult(roleId: string, seasonNum: number, update: PvpSeasonResultUpdate , lean = true) {
        delete update._id;
        let result: PvpSeasonResultType = await PvpSeasonResultModel.findOneAndUpdate({roleId, seasonNum}, {$set: update}, {upsert: true, new: true}).lean(lean);
        return result;
    }

    public static async setShow(roleId: string) {
        let result = await PvpSeasonResultModel.updateMany({ roleId, show: true }, { show: false }).lean();
        return result;
    }

    public static async getPvpSeasonResult(roleId: string) {
        let result: PvpSeasonResultType = await PvpSeasonResultModel.findOne({ roleId, show: true }).lean();
        return result;
    }

    public static async checkResultBySeasonNum(roleId: string, seasonNum: number) {
        return await PvpSeasonResultModel.exists({ roleId, seasonNum });
    }
}

export const PvpSeasonResultModel = getModelForClass(PvpSeasonResult);

export interface PvpSeasonResultType extends Pick<DocumentType<PvpSeasonResult>, keyof PvpSeasonResult> { };
export type PvpSeasonResultUpdate = Partial<PvpSeasonResultType>;