import { app } from "../App";
import { API, PlayerTacticalOV } from "../consts/API";
import BaseData from "./BaseData";
import { GBattleDataEnum } from "./GBattleData";
import GOnHookData from "./GOnHookData";
import PlayerPetData from "./PlayerPetData";

export enum PlayerTacticalEvent{
    //更新上阵信息
    UPDATE_TACTICAL = "PlayerTacticalEvent_UPDATE_TACTICAL"
}

interface PlayerTacticalInfo extends PlayerTacticalOV{
    roles:number[], //上阵的宠物顺序
}

//玩家阵法数据 (玩家最多上阵 9 个宠物)
export default class PlayerTacticalData extends BaseData{

    //阵法信息
    info:PlayerTacticalInfo;

    async onInit() {

        await this.onUpdateInfo();

    }

    //保存阵法信息
    onSaveTacticalInfo(ov:PlayerTacticalOV){

        if(!ov.tacticalData){
            ov.tacticalData = JSON.stringify(this.getInitTacticalInfo());
        }
        this.info = {
            ...ov,
            roles: JSON.parse(ov.tacticalData).map(id => PlayerPetData.getIns().petIdQueryPetInfo(id) ? id : 0),
        }
        
        app.event.emit(GBattleDataEnum.UPDARE_ATTRIBUTE); //刷新属性

        //通知阵法信息已更新
        app.event.emit(PlayerTacticalEvent.UPDATE_TACTICAL);

    }

    //更新阵法信息
    async onUpdateInfo(){
        this.onSaveTacticalInfo(await API.GetPlayerTactical());
    }

    //更新上阵
    async UpdateTactical(roles:number[]):Promise<boolean>{
        //如果阵法一样则不更新
        if(this.info.tacticalData == JSON.stringify(roles)) return false;
        this.info.roles = roles;
        this.info.tacticalData = JSON.stringify(this.info.roles);
        //上传到服务器 并且保存
        this.onSaveTacticalInfo(await API.SetPlayerTactical(this.info));
        return true;
    }

    //修改指定位置的上阵 上阵下标,上阵的宠物Id
    async UpdateIndexTactical(index:number,petId:number){
        this.info.roles = this.info.roles.map(id => petId == id ? 0 : id);
        this.info.roles[index] = petId;
        await this.UpdateTactical(this.info.roles);
    }

    //获取指定位置
    getItem(index:number){
        return this.info.roles[index];
    }

    //获取宠物的阵法下标
    getItemIndex(roleId:number){
        return this.info.roles.indexOf(roleId);
    }

    //获取初始化上阵信息
    getInitTacticalInfo():number[]{
        return [0,0,0,0,0,0,0,0,0]
    }
    getTacticalInfo():number[]{
        return this.info.roles;
    }

}