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

@index({ createdAt: 1, cityId: 1, serverId: 1,  })
export default class GuildActivityCity extends BaseModel {

    @prop({ required: true })
    serverId: number;       // 分服
    
    @prop({ required: true })
    cityId: number;       // 城池id

    @prop({ required: true })
    declareIndex: number;       // 城池id

    @prop({ required: true, type: String, default: [] })
    declareGuilds: string[];       // 宣战的公会的code

    @prop({ required: true, default: 0 })
    declareCount: number;       // 宣战数量

    @prop({ required: true, default: "" })
    guardGuildCode: string;       // 占领的军团的code

    @prop({ required: true, default: "" })
    guardGuildName: string;       // 占领的军团名

    @prop({ required: true })
    guardTime: Date;       // 占领日期

    @prop({ required: true })
    status: number;       // 0-过去的 1-现在的 2-未来的

    // 每天宣战一次
    public static async getAllCities(serverId: number, declareIndex: number) {
        let rec: GuildActivityCityType[] = await GuildActivityCityModel.find({ serverId, status: 1, declareIndex }).lean();
        
        return rec;
    }

    public static async findMinDeclareCountCity(serverId: number, cityIds: number[], declareIndex: number) {
        let rec: GuildActivityCityType[] = await GuildActivityCityModel.find({ serverId, cityId: { $in: cityIds }, status: 1, declareIndex }).sort({ declareCount: 1 }).lean();
        return rec;
    }

    public static async getCity(serverId: number, cityId: number, declareIndex: number) {
        let rec: GuildActivityCityType = await GuildActivityCityModel.findOne({ serverId, cityId, status: 1, declareIndex }).lean();
        
        return rec;
    }

    // 宣言
    public static async declare(serverId: number, cityId: number, guildCode: string, declareIndex: number) {
        let rec: GuildActivityCityType = await GuildActivityCityModel.findOneAndUpdate(
            { serverId, cityId, status: 1, declareIndex }, 
            { $push: { declareGuilds: guildCode }, $inc: {declareCount: 1 } }, 
            {new: true, upsert: true}).lean();

        return rec;
    }

    // 占领
    public static async guard(serverId: number, cityId: number, guildCode: string, guildName: string, declareIndex: number) {
        let rec: GuildActivityCityType = await GuildActivityCityModel.findOneAndUpdate(
            { serverId, cityId, status: 1, declareIndex }, 
            { $set: { guardGuildCode: guildCode, guardGuildName: guildName, guardTime: new Date()} }, 
            { new: true, upsert: true }).lean();
        return rec;
    }
}

export const GuildActivityCityModel = getModelForClass(GuildActivityCity);

export interface GuildActivityCityType extends Pick<DocumentType<GuildActivityCity>, keyof GuildActivityCity> { };
export type GuildActivityCityUpdateParam = Partial<GuildActivityCityType>; // 将所有字段变成可选项