using Fort23.Mono;
using UnityEngine;
using UnityEngine.Rendering.Universal;

public class CustomCameraStack : MonoBehaviour
{
    private UniversalAdditionalCameraData _cameraData;
    public Camera camera;

    public static CustomCameraStack currCustomCameraStack;

    private void OnEnable()
    {
        currCustomCameraStack = this;
        SetUICamera();
        camera = GetComponent<Camera>();
    }

    public void SetUICamera()
    {
        if (UIManager.Instance != null && UIManager.Instance.UICamera != null)
        {
            UniversalAdditionalCameraData cameraData = UIManager.Instance.UICamera.gameObject.GetComponent<UniversalAdditionalCameraData>();
            if (cameraData != null)
            {
                UIManager.Instance.CurrCustomCameraStack = this;
                cameraData.renderType = CameraRenderType.Overlay;
            }

            AddCamera(UIManager.Instance.UICamera);
        }
    }

    private void Update()
    {
        if (currCustomCameraStack == this && UIManager.Instance != null && UIManager.Instance.CurrCustomCameraStack == null)
        {
            SetUICamera();
        }
    }

    public void AddCamera(Camera camera)
    {
        if (_cameraData == null)
        {
            _cameraData = GetComponent<Camera>().GetUniversalAdditionalCameraData();
        }

        if (!_cameraData.cameraStack.Contains(camera))
        {
            _cameraData.cameraStack.Add(camera);
        }
    }

    public void RemoveCamera(Camera camera)
    {
        if (_cameraData == null)
        {
            _cameraData = GetComponent<Camera>().GetUniversalAdditionalCameraData();
        }

        if (_cameraData.cameraStack.Contains(camera))
        {
            _cameraData.cameraStack.Remove(camera);
        }
    }

    private void OnDisable()
    {
        if (_cameraData != null && _cameraData.cameraStack != null && _cameraData.cameraStack[^1] != null && UIManager.Instance.CurrCustomCameraStack == this)
        {
            UniversalAdditionalCameraData cameraData = _cameraData.cameraStack[^1].gameObject.GetComponent<UniversalAdditionalCameraData>();
            if (cameraData != null)
            {
                cameraData.renderType = CameraRenderType.Base;
            }

            UIManager.Instance.CurrCustomCameraStack = null;
        }

        _cameraData.cameraStack.Clear();
    }
}