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


@index({ roleId: 1, battleId: 1 })

export default class RScriptRecord extends BaseModel {
  @prop({ required: true, default: '' })
  roleId: string;					// 角色 id

  @prop({ required: true, default: 0 })
  battleId: number;				    // 关卡 id
  @prop({ required: true, default: 0 })
  warType: number;				    // 关卡 id

  @prop({ required: true, default: '' })
  scriptBefore: string;             // 战场前剧本

  @prop({ required: true, default: '' })
  scriptAfter: string;              // 战场后剧本


  public static async setScript(roleId: string, battleId: number, warType: number, type: number, script: string, lean = true) {
     let update = { warType };
      if(type == 1) {
        update['scriptBefore'] = script;
      } else if (type == 2) {
        update['scriptAfter'] = script;
      }
      
    const items: RScriptRecordType = await RScriptRecordModel.findOneAndUpdate({ roleId, battleId }, update, {upsert: true, new: true}).lean(lean);
    return items;
  }

  public static async findbyRoleAndBattle(roleId: string, battleId: number, lean = true) {
    const items: RScriptRecordType = await RScriptRecordModel.findOne({ roleId, battleId }).select('battleId scriptBefore scriptAfter').sort({battleId: 1}).lean(lean);
    return items;
  }

  public static async findbyRole(roleId: string, warType: number, lean = true) {
    const items: RScriptRecordType[] = await RScriptRecordModel.find({ roleId, warType }).select('battleId scriptBefore scriptAfter').lean(lean);
    return items;
  }
}

export const RScriptRecordModel = getModelForClass(RScriptRecord);

export interface RScriptRecordType extends Pick<DocumentType<RScriptRecord>, keyof RScriptRecord>{};