using System;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Scripting;

namespace TyphoonUnitySDK
{
    [Preserve]
    public class HuaweiHarmonyCallback : MonoBehaviour
    {
        private Action<string> OnReceiveMessage { get; set; }

        public static HuaweiHarmonyCallback CreateInstance()
        {
            var clone = new GameObject("HuaweiHarmonyCallback");
            var result = clone.AddComponent<HuaweiHarmonyCallback>();
            DontDestroyOnLoad(clone);
            return result;
        }

        public void Initialize(Action<string> onReceive)
        {
            OnReceiveMessage = onReceive;
            SdkDebug.Log("HuaweiHarmonyCallback initialized");
        }

        private void OnReceiveHarmonyMessage(string message)
        {
            SdkDebug.Log($"OnReceiveHarmonyMessage message = {message}");
            OnReceiveMessage?.Invoke(message);
        }

        private void OnReceiveSessionMessage(string json)
        {
            //{"sessionId":1,"data":{"state":"ok"}}
            SdkDebug.Log($"OnReceiveSessionMessage message = {json}");
            var jObject = JObject.Parse(json);
            var sessionId = jObject["sessionId"].ToLong();
            var dataJson = jObject["data"]?.ToString();
            SessionItem.Invoke(sessionId, dataJson);
        }
    }
}