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

export class ScienceTree {
    @prop({ required: true })
    id: number;
    @prop({ required: true })
    endTime: number;//科技树研发成功结束事件，时间戳，小于当前时间，说明开发完成
    @prop({ required: true, default: [], type: String, _id: false})
    assistRoleIds: Array<string>;	//协助完成的玩家roleId
}

@index({ guildCode: 1 })

export default class GuildRefine extends BaseModel {
    @prop({ required: true })
    guildCode: string;					

    @prop({ required: true, type: ScienceTree, default:[] })
    scienceTrees: ScienceTree[];     //科技树解锁情况  

    public static async createScienceTree(guildCode: string, scienceTrees: ScienceTree[], lean = true) {
        const result = await GuildRefineModel.findOneAndUpdate({ guildCode }, {$set: {scienceTrees}}, {new: true, upsert: true}).lean(lean);
        return result;
    }

    public static async getRefine(guildCode: string, lean = true) {
        const result = await GuildRefineModel.findOne({ guildCode }).lean(lean);
        return result;
    }
    
    public static async pushRefine(guildCode: string, scienceTree: ScienceTree,lean = true) {
        const result = await GuildRefineModel.findOneAndUpdate({ guildCode,  'scienceTrees.$.id':{$ne:scienceTree.id}}, {$push: {scienceTrees: scienceTree}}, { new: true }).lean(lean);
        return result;
    }

    public static async updateRefine(guildCode: string, update: GuildRefineTypeParam, lean = true) {
        const result = await GuildRefineModel.findOneAndUpdate({ guildCode}, {$set: update}, { new: true }).lean(lean);
        return result;
    }
}

export const GuildRefineModel = getModelForClass(GuildRefine)
export interface GuildRefineType extends Pick<DocumentType<GuildRefine>, keyof GuildRefine> { };

export type GuildRefineTypeParam = Partial<GuildRefineType>; // 将所有字段变成可选项
