using System.Collections.Generic;
using IgnoreOPS;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

namespace ChillConnect
{
    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) {
            NetApi.RequestPlayerData((isSuccess, json) => {
                // Debug.Log($"barry UserData : {json}");
                if (isSuccess) {
                    var loginModel = LoginKit.Instance.LoginModel;
                    if (loginModel.NewPlayer || loginModel.Uid != DataMgr.UserID.Value)
                    {
                        SaveLocalData.clearRankData();
                        GameHelper.clearJsonData();
                    }
                    DataMgr.InitPreferences(json);
                    NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetConfig);
                }
                else {
                    Debug.LogError($"OnRequestPlayData isError {json}");
                }
            });
        }

        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 != default)
                    {
                        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();
        }
    }
}