using System.Collections.Generic;
using UnityEngine;
using GameAnalyticsSDK;
using Touka.GameLogic;

public partial class StaticOnlineParams :ToukaSingletonMonoBehaviour<StaticOnlineParams>{

    public void Init () {
        // init all params, from local saved
        InitAllParams();
    }

    private void InitAllParams()
    {
        InitAllGameParams();
    }

    #region Save & Get value

    /// <summary>
    /// save online value by string
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_value"></param>
    public void SaveOnlineValue2Local(string _key, string _value)
    {
        ToukaUtils.SavePlayerPrefsStringByKeyValue(_key, _value);
    }

    /// <summary>
    /// get online value by string
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_defaultValue"></param>
    /// <returns></returns>
    public string GetOnlineValueFromLocal(string _key, string _defaultValue)
    {
        string tempValue = ToukaUtils.GetPlayerPrefsStringByKey(_key, _defaultValue);
        return tempValue;
    }

#endregion

}

public class ToukaOnlineParam {
    public string Key;      // key
    public bool needUploadDirectly = true;          // 获取到在线参数后是否立刻上传，默认：是

    private string defaultValue;
    public string DefaultValue      // value
    {
        get
        {
            string tempOnlineValue = TGTools.Instance.ConfigValueForKey(Key);
            Debug.Log("value ----- tempOnlineValue : " + tempOnlineValue);
            if (!string.IsNullOrEmpty(tempOnlineValue))        // 实时取一下在线参数
            {
                UpdateValueByKey(tempOnlineValue);
            }

            return defaultValue;
        }
        set
        {
            defaultValue = value;
        }
    }

    public ToukaOnlineParam (string _key, string _defaultValue, bool _uploadDirectly = true) {
        Key = _key;
        DefaultValue = _defaultValue;
        needUploadDirectly = _uploadDirectly;
    }

    /// <summary>
    /// 拿到在线参数后，更新数据
    /// </summary>
    /// <param name="newValue"></param>
    public void UpdateValueByKey(string newValue)
    {
        DefaultValue = newValue;        // 赋值

        if (needUploadDirectly)        // 若需要，则上报
        {
            ToukaAnalyticsManager.Instance.LogEventByUmeng(string.Format("{0}_{1}", Key, newValue));
        }

        StaticOnlineParams.Instance.SaveOnlineValue2Local(Key, newValue);        // 本地缓存
    }

    
    /// <summary>
    /// 初始化参数
    /// </summary>
    /// <param name="_newValue"></param>
    public void InitValue(string _newValue)
    {
        DefaultValue = _newValue;        // 赋值
    }
}
