using System.Collections.Generic;
using BingoBrain;
using BingoBrain.Core;
using UnityEngine;


public class PlayDataSystem : BaseSystem
{
    public PlayDataSystem(bool isAutoInit = true)
    {
        if (isAutoInit)
        {
            Init();
        }
    }

    public sealed override void Init()
    {
        base.Init();


        AddListener();
    }

    private void AddListener()
    {
        NetworkDispatcher.Instance.AddListener(NetworkMsg.GetPlayData, OnRequestPlayData);
        NetworkDispatcher.Instance.AddListener(NetworkMsg.SavePlayData, OnRequestSavePlayData);
    }

    private void RemoveListener()
    {
        NetworkDispatcher.Instance.RemoveListener(NetworkMsg.GetPlayData, OnRequestPlayData);
        NetworkDispatcher.Instance.RemoveListener(NetworkMsg.SavePlayData, OnRequestSavePlayData);
    }

    private void OnRequestPlayData(object args)
    {
        NetworkKit.PostWithHeader<Preferences>("user/userData", (isSuccess, obj) =>
        {
            var loginModel = GameHelper.GetLoginModel();
            loginModel.preferences = obj;

            PreferencesMgr.Instance.InitPreferences();
            NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetConfig);

        });
    }

    private void OnRequestSavePlayData(object obj)
    {
        if (obj != null)
        {
            var msg = obj as Dictionary<string, object>;

            if (msg == null)
            {
                return;
            }

            var version = 1L;
            if (msg.TryGetValue("data_ver", out var ver))
            {
                if (version != null)
                {
                    version = (long)ver;
                }
            }

            var data = SerializeUtil.ToJson<Dictionary<string, object>>(msg);

            var requestData = new RequestSavePlayData
            {
                version = version,
                data = data
            };
            NetworkKit.PostWithHeader("user/updateData", requestData);
        }
    }

    public override void Dispose()
    {
        base.Dispose();
        RemoveListener();
    }
}
public class RequestSavePlayData
{
    public long version;
    public string data;
}
