import { Framework } from "../../framework/Framework";
import { ObjectUtil } from "../../framework/util/ObjectUtil";
import { StringUtil } from "../../framework/util/StringUtil";
import { GameEvent } from "./GameEvent";

export const DataKey = {
    Role: "Role",                           //角色
    GameInstall: "GameInstall",             //设置
    UserID: 'UserID',                       //用户ID
};

class Data {
    private _class_id = StringUtil.getUUID(32);
    //需要保存的数据
    save_data = new Map<string, any>();

    UserID: any = null;
    init(user_uuid: string, data: any) {
        Framework.storage.setUser(user_uuid);
        

        //将服务器的数据替换到本地
        // let save = new Map<string, string>();
        for (let key in data) {
            this[key] = data[key]
            Framework.storage.set(key, this[key]);
        }
        //读取本地数据
        //this.era = Framework.storage.get(DataKey.Era, GameConf.Macro.default_era);
        //兼容代码
        Framework.event.addEvent(GameEvent.Daily_Update, () => {
            // Framework.event.fireEvent(GameEvent.Daily_Update);
            //每日凌晨更新事件
            //    
        }, this, this._class_id);

    }

    // 存储本地
    save_locally(key: string, value?, defaultValue?: any) {
        if (key != 'UserID') {
            key += this.UserID
        }
        if (value) {
            this[key] = value
            Framework.storage.set(key, value);
            this._saveData(key, value)
        } else {
            this[key] = Framework.storage.get(key, defaultValue);
            return this[key];
        }
    }

    _saveData(key: string, value: any) {
        this.save_data.delete(key);
        if (typeof value === 'object') {
            try {
                if (value instanceof Map) {
                    let temp = ObjectUtil.mapToObject(value)
                    value = JSON.stringify(temp);
                } else {
                    value = JSON.stringify(value);
                }
            } catch (e) {
                console.error(`解析失败,str = ${value}`);
                return;
            }
        } else {
            value = value + "";
        }
        this.save_data.set(key, value);
        Framework.storage.set('save_data', this.save_data);
    }

    private _mapToObject(map: any) {
        let obj = {};
        for (let [k, v] of map) {
            obj[k] = v;
        }
        return obj;
    }

}

export let UserData = new Data;