using System;
using Assets.Source.Constants;
using Assets.Source.UI.Elements;
using Assets.Source.UI.Layers;
using UnityEngine;

namespace Assets.Source.UI
{
    public class UICanvasController : MonoBehaviour
    {
        public UIPanelLayer PanelLayer;
        public UIDialogueLayer DialogueLayer;

        private Canvas _canvas;

        void Awake()
        {
            PanelLayer.Init();
            DialogueLayer.Init();
            _canvas = GetComponent<Canvas>();
            //_canvas.worldCamera = Get.GameCamera.Camera;
        }
        
        public T OpenPanel<T>(string explicitId, IUIElementProperties properties = null, bool instantly = false) where T : IUIPanel
        {
            return PanelLayer.Open<T, IUIElementProperties>(explicitId, properties, instantly);
        }
        public T OpenPanel<T>(IUIElementProperties properties = null, bool instantly = false) where T : IUIPanel
        {
            return OpenPanel<T>(UIConstants.DEFAULT_EXPLICIT_ID, properties, instantly);
        }

        public T OpenDialogue<T>(string explicitId, IUIElementProperties properties = null, bool instantly = false) where T : IUIDialogue
        {
            return DialogueLayer.Open<T, IUIElementProperties>(explicitId, properties, instantly);
        }
        public T OpenDialogue<T>(IUIElementProperties properties = null, bool instantly = false) where T : IUIDialogue
        {
            return OpenDialogue<T>(UIConstants.DEFAULT_EXPLICIT_ID, properties, instantly);
        }

        public T Open<T>(string explicitId, IUIElementProperties properties = null, bool instantly = false) where T : IUIElement
        {
            var type = typeof(T);
            var e = DialogueLayer.Open(type, explicitId) ?? PanelLayer.Open(type, explicitId);
            return e != null ? (T)e : default(T);
        }

        public IUIElement Open(Type type, string explicitId)
        {
            return
                DialogueLayer.Open(type, explicitId) ??
                PanelLayer.Open(type, explicitId);
        }
        public IUIElement Open(Type type)
        {
            return Open(type, UIConstants.DEFAULT_EXPLICIT_ID);
        }

        public IUIElement TryClose(Type type, string explicitId)
        {
            return 
                DialogueLayer.Close(type, explicitId) ?? 
                PanelLayer.Close(type, explicitId);
        }

        public IUIElement TryClose(Type type)
        {
            return TryClose(type, UIConstants.DEFAULT_EXPLICIT_ID);
        }

        public IUIElement Close<T>(string explicitId = null) where T : IUIElement
        {
            var type = typeof(T);
            return
                DialogueLayer.Close(type, explicitId) ??
                PanelLayer.Close(type, explicitId);
        }
    }
}
