import { _decorator, Label} from 'cc';
import { constants } from '../data/constants';
const { ccclass, property } = _decorator;

@ccclass('stateManager')
export class stateManager {
    private static instance: stateManager;
    //存储状态字段与 UI 组件的绑定关系
    private uiBindings: Map<string, Label[]> = new Map();

    //获取单例实例
    public static ins() {
        if (!this.instance) {
            this.instance = new stateManager();
        }
        return this.instance;
    }
    
    /**
     * 注册UI组件
     * @param field 注册的key uiName
     * @param label 具体的文本
     */
    public registerUI(field: string, label: Label|any): void {
        if (!this.uiBindings.has(field)) {
            this.uiBindings.set(field, []);
        }
        //将UI组件添加到绑定列表
        let uiArr:Array<any> = this.uiBindings.get(field);
        if(!uiArr.includes(label)){
            uiArr.push(label);
        }
        //初始化UI显示
        this.updateSingleUI(field, label); 
    }

    /**
     * 全局更新所有绑定该字段
     * @param field 注册的key uiName
     */
    public updateAllUI(field: string): void {
        let labels:Array<any> = this.uiBindings.get(field);
        if (labels) {
            labels.forEach(label => {
                this.updateSingleUI(field, label);
            });
        }
    }

    /**
     * 更新单个UI组件
     * @param field 
     * @param label 
     */
    private updateSingleUI(field: string, com: Label|any): void {
        if(field == constants.playerInfoData){//玩家信息变化
            //com.string = `${storageData.pureCount}`;
            //com.refreshData();
        }else if(field == constants.playerName){//玩家名字变化
        }
    }
}
export default stateManager.ins();