import { app } from "../App";
import { API, ResourceOV } from "../consts/API";
import BaseData from "./BaseData";

export enum ResourceEvent{
    UPDATE = "ResourceEvent_UPDATE",    //刷新资源
}

//资源类型
export enum ResourceType{
    Gold = 90001,                   //金币
    ForgedStones = 90002,           //锻造石
    SpeedUp = 90003,                //加速卷
    DungeonGold = 90004,            //钥匙:金币副本
    DungeonForgedStones = 90005,    //钥匙:锻造石副本
    Q1S = 90006,                    //魂:一品宠物魂
    GiftCoupons = 90007,            //兑换券
}

//资源刷新类型
export enum ResourceUpdateType{
    UPDATE = 0,  //刷新资源数量
    MINUS = 1,   //减少资源数量
    ADD = 2,     //添加资源数量
}

//资源信息

//玩家资源数据
export default class ResourceData extends BaseData{

    //资源数据 {资源Id:资源数量}
    data:{[key:number]:number} = {};

    //资源更新的版本号
    versions:{[key:number]:number} = {};

    //初始化
    async onInit() {
        await this.onUpdateResource();
    }

    //更新玩家资源
    async onUpdateResource(){

        //请求资源
        let res = await API.GetPlayerResource();

        //保存资源数量
        res.forEach(data => {
            this.data[data.resourceTbId] = data.resourceValue;
        })

    }

    //获取所有资源Id
    getIds():number[]{
        return Object.keys(this.data).map(id => parseInt(id));
    }

    //获取指定资源的数量
    getValue(type:ResourceType){
        return this.data[type] || 0;
    }

    //更新资源
    onResource(resource:ResourceOV){
        let version = this.versions[resource.resourceTbId] || 0;
        if(resource.version >= version){
            version = this.versions[resource.resourceTbId] = resource.version;
            this.data[resource.resourceTbId] = resource.resourceValue;
            app.event.emit(ResourceEvent.UPDATE,this.data[resource.resourceTbId])
        }
    }

    //刷新返回资源
    onUpdateOV(operation:number,resource:ResourceOV){

        //如果没有刷新的资源 则 返回
        if(!resource) return;

        if(operation == ResourceUpdateType.UPDATE){
            this.onResource(resource);
        }

    }


}


