import { GOnHookPet } from "../../../../../extensions/ngame/assets/ngame/message/proto";
import NGameUtil from "../../../../../extensions/ngame/assets/ngame/util/NGameUtil";
import { NSystemEvent } from "../../../../../extensions/ngame/assets/ngame/util/NSystem";
import Singleton from "../../../../../extensions/ngame/assets/ngame/util/Singleton";
import { TD, app } from "../../../App";
import GBattleModeManager, { BattleMode } from "../../../battle/GBattleModeManager";
import { TB } from "../../../config/data/schema";
import { API, PlayerPetOV } from "../../../consts/API";
import { GAPI } from "../../../consts/GAPI";
import GOnHookData from "../../../data/GOnHookData";
import PlayerPetData from "../../../data/PlayerPetData";
import PlayerTacticalData from "../../../data/PlayerTacticalData";
import { GUI } from "../../../ui/UIConfig";

export enum GOnHookManagerEvent{
    //添加死亡野怪
    ADD_KILL_SREEP = "GOnHookManagerEvent_ADD_KILL_SREEP",
    //删除死亡野怪
    DEL_KILL_SREEP = "GOnHookManagerEvent_DEL_KILL_SREEP",
    //重置数据
    RESET_DATA = "GOnHookManagerEvent_RESET_DATA",
    //删除死亡野怪
    UPDATE_MAP = "GOnHookManagerEvent_UPDATE_MAP",
    //更新挂机状态
    UPDATE_ON_HOOK_STATE = "GOnHookManagerEvent_UPDATE_ON_HOOK_STATE"
}

//游戏模式 OnHook 管理器
export default class GOnHookManager extends Singleton{

    isSpawn:boolean = false;

    //野怪列表
    _sreeps:Map<string,GOnHookPet> = new Map();
    get sreeps(){
        //如果没有野怪了 则 向服务器生成
        if(!this._sreeps || !(this._sreeps.size)){
            //生成
            this.onSpawnSreeps();
            return new Map();
        }
        return this._sreeps;
    }
    set sreeps(data:Map<string,GOnHookPet>){
        this._sreeps = data;
    }

    //已经死亡的野怪列表
    killSreeps:GOnHookPet[] = [];

    //-------------------------- 挂机 ---------------------------------

    //需要捕捉的宠物
    onHookCatchPets:TB.TbGRole[] = [];
    //是否自动下一关
    isAutoNext:boolean = false;

    //是否挂机
    _isOnHook:boolean = false;
    get isOnHook(){return this._isOnHook}
    set isOnHook(value:boolean){
        this._isOnHook = value; 
        //通知更新挂机状态
        app.event.emit(GOnHookManagerEvent.UPDATE_ON_HOOK_STATE);
    }

    init(){
        app.event.on(NSystemEvent.UPDATE,this.onUpdate,this);
    }

    destroy(): void {
        app.event.off(NSystemEvent.UPDATE,this.onUpdate,this);
    }

    onUpdate(){
        this.onUpdateOnHook();
    }

    //更新挂机
    onUpdateOnHook = NGameUtil.ThrottleASync((async () => {

        //如果是挂机 则 出售不需要捕捉的宠物
        if(!this.isOnHook) return;

        //捕捉 和 出售
        let pet = this.killSreeps[0];
        if(pet){
            if(this.onHookCatchPets.indexOf(TD.TbGRole.get(pet.petTbId)) >= 0){
                //捕捉
                await this.onCatchCreeps(pet)
            }else{
                //出售
                await this.onSellCreeps(pet)
            }
        }
        
    }).bind(this))

    //生成野怪
    onSpawnSreeps = NGameUtil.ThrottleASync((async () => {
        let data = await GAPI.GOnHookSpawnCreeps();
        if(!data) return;
        this._sreeps = new Map();
        let ids = this.getKillSreepsIds();
        data.pets.forEach(pet => {
            if(ids.indexOf(pet.key) < 0){
                this._sreeps.set(pet.key,pet as GOnHookPet);
            }
        })
    }).bind(this))

    //获取下一只野怪
    getNextCreeps(){
        if(this.getKillSreepsIds().length > 50) return;
        if(!this.sreeps) return;
        let creeps = this.sreeps.get(this.sreeps.keys().next()?.value);
        this.sreeps.delete(creeps.key);
        return creeps;
    }

    //获取已经死亡待处理的野怪Id列表
    getKillSreepsIds(){
        return this.killSreeps.map(item => item.key);
    }

    //野怪死亡
    onKillSreeps(creeps:GOnHookPet){

        this.sreeps.delete(creeps.key);
        //记入死亡
        //判断是否在死亡中如果在则跳出
        if(this.killSreeps.indexOf(creeps) > -1){
            return;
        }        
        this.killSreeps.push(creeps);

        //通知添加死亡野怪
        app.event.emit(GOnHookManagerEvent.ADD_KILL_SREEP,creeps);

        console.log(`GOnHookManager : ${creeps.key} 宠物死亡 可进行捕捉 出售`);

    }

    //捕捉野怪
    async onCatchCreeps(creeps:GOnHookPet):Promise<boolean>{
        
        let index;
        if((index = this.killSreeps.indexOf(creeps)) < 0){
            app.layer.Open(GUI.Tips,{text:"不可捕捉该野怪"});
            return false;
        }

        //删除
        this.killSreeps.splice(index,1);

        //通知添加野怪被删除
        app.event.emit(GOnHookManagerEvent.DEL_KILL_SREEP,creeps);

        return !!await GAPI.GOnHookCatchCreeps(creeps.key);

    }

    //出售野怪
    async onSellCreeps(creeps:GOnHookPet):Promise<boolean>{

        let index;
        if((index = this.killSreeps.indexOf(creeps)) < 0){
            app.layer.Open(GUI.Tips,{text:"不可出售当前野怪"});
            return false;
        }

        //删除
        this.killSreeps.splice(index,1);

        app.event.emit(GOnHookManagerEvent.DEL_KILL_SREEP,creeps);
        // //通知添加野怪被删除
        // if(await GAPI.GOnHookSellCreeps(creeps.key)){
        //     return true;
        // }else{
        // }
        return await GAPI.GOnHookSellCreeps(creeps.key);
    }

    //重置数据
    onResetData(){
        this._sreeps = new Map();
        this.killSreeps = [];
        app.event.emit(GOnHookManagerEvent.RESET_DATA);
    }

    //重置Sreeps
    onResetSreeps(){
        this._sreeps = new Map();
    }

    //下一关
    async onNextLevel(){
        await GOnHookData.getIns().onNextLevel();
        this.onResetMap();
    }

    //战胜当前关卡
    async onWinLevel(){
        await GOnHookData.getIns().onWinLevel();
        //如果在自动挂机并且勾选上了自动下一关 则 自动下一关
        if(this.isOnHook && this.isAutoNext && GOnHookData.getIns().isNextLevel) this.onNextLevel();
    }

    //切换场景
    async setMap(mapId:number){

        await GOnHookData.getIns().setMap(mapId);
        this.onResetMap();

    }

    //重置场景
    onResetMap(){
        //通知地图已切换
        app.event.emit(GOnHookManagerEvent.UPDATE_MAP);
        //重置Sreeps数据
        this.onResetSreeps();
        //重置场景
        GBattleModeManager.getIns().Open(BattleMode.OnHook,true);
    }


}


