﻿using System;
using System.Collections.Generic;
using UnityEngine;
using MiniJSON;

namespace Stove.StoveSDK
{
    public class StoveSDK : MonoBehaviour
    {
        static StoveSDK instance;
        public static StoveSDK Instance
        {
            get
            {
                if (instance == null)
                {
                    GameObject gameObject = new GameObject("StoveSDK");
                    instance = gameObject.AddComponent<StoveSDK>();
                }
                return instance;
            }
        }

        private Dictionary<string, Action<Dictionary<string, object>>> actionDic = new Dictionary<string, Action<Dictionary<string, object>>>();

        private void Awake()
        {
            if (instance == null)
            {
                instance = this;
            }
            else if (instance != this)
            {
                Destroy(gameObject);
            }
            DontDestroyOnLoad(gameObject);
        }

        internal string AddAction(Action<Dictionary<string, object>> action)
        {
            string identifier = Guid.NewGuid().ToString();
            actionDic.Add(identifier, action);

            return identifier;
        }

        public void CallMessage(string message)
        {
            var payload = Json.Deserialize(message) as Dictionary<string, object>;

            string identifier = payload["identifier"] as string;
            var value = payload["value"] as Dictionary<string, object>;

            Action<Dictionary<string, object>> callback = null;
            if (actionDic.TryGetValue(identifier, out callback))
            {
                actionDic.Remove(identifier);
            }

            if (callback != null)
            {
                callback.Invoke(value);
            }
        }

        public void NotifyMessage(string message)
        {
            var payload = Json.Deserialize(message) as Dictionary<string, object>;

            string identifier = payload["identifier"] as string;
            var value = payload["value"] as Dictionary<string, object>;

            Action<Dictionary<string, object>> callback = actionDic[identifier] as Action<Dictionary<string, object>>;
            
            if (callback != null)
            {
                callback.Invoke(value);
            }
        }
    }
}
