using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.Events;

public class UIManager : IManager
{
    private Canvas _canvas;
    private List<string> _uiList = new ();
    public List<string> UIList
    {
        get { return _uiList; }
        set
        {
            _uiList = value ?? new List<string>();
            foreach (var ui in _uiList)
            {
                string path = Define.MapPath(ui);
                CreateObject(path, ui);
            }
        }
    }
    
    private readonly Dictionary<string, GameObject> _objects = new ();
    private readonly Dictionary<string, GameObject> _instances = new();
    private readonly Dictionary<string, bool> _switchObjects = new ();

    private Dictionary<string, Action<string, float, float>> _registeredBarActions = new ();
    
    
    public void Init()
    {
        _canvas = GameObject.Find("@Canvas").GetComponent<Canvas>();
    }

    private void CreateObject(string path, string prefabName)
    {
        GameObject createObj = Manager.Resource.Load<GameObject>(path);
        if (createObj != null)
        {
            _objects.Add(prefabName, createObj);
            _switchObjects.Add(prefabName, false);
        }
    }

    public T SwitchOnObject<T>(string name, bool isOn) where T : MonoBehaviour
    {
        if (_switchObjects.ContainsKey(name) && (_switchObjects[name] != isOn))
            _switchObjects[name] = isOn;
        else return null;

        GameObject instance;
        if (!_instances.ContainsKey(name))
        {
            instance = Manager.Resource.Instantiate(_objects[name], _canvas.transform);
            // instance.name = name;
            _instances.Add(name, instance);
        }
        else instance = _instances[name];
        
        if (_switchObjects.ContainsKey(name) && _switchObjects[name])
        {
            instance.SetActive(true);
        }
        else
        {
            instance.SetActive(false);
        }
        
        T component = instance.GetComponent<T>();
        // if (action != null && component is UIButton button) button.Bind(action);
        
        // if (component is UIButton button) Manager.Input.Buttons.Add(name, button);

        return component;
    }

    #region UI Object 특화 메서드
    
    #region Bar 메서드
    public void SubscribeToBarAction(string name, Action<string, float, float> action)
    {
        if (!_registeredBarActions.ContainsKey(name)) _registeredBarActions[name] = null;
        _registeredBarActions[name] -= action;
        _registeredBarActions[name] += action;
    }

    public Action<string, float, float> GetBarAction(string name)
    {
        _registeredBarActions.TryGetValue(name, out var action);
        return action;
    }
    #endregion
    
    #endregion
}
