using System;
using FairyGUI;
using UnityEngine;
using UnityEngine.Rendering.Universal;

namespace NBF
{
    public class BaseCamera : MonoBehaviour
    {
        public static Camera Main { get; private set; }

        public static UniversalAdditionalCameraData MainCameraData { get; private set; }

        private void Awake()
        {
            #if CINEMACHINE_URP
            int i = 0;
            #endif
            Init();
            DontDestroyOnLoad(gameObject);
            DepthOfField dof = ScriptableObject.CreateInstance<DepthOfField>();
            dof.aperture.value = 0;
            dof.focalLength.value = 0;
        }

        public void Init()
        {
            Main = GetComponent<Camera>();
            MainCameraData = Main.GetUniversalAdditionalCameraData();
        }


        private static void FixUICamera()
        {
            if (StageCamera.main == null) return;
            var stageCameraData = StageCamera.main.GetUniversalAdditionalCameraData();
            if (stageCameraData != null)
            {
                if (MainCameraData.cameraStack.Contains(StageCamera.main)) // 防止重复添加
                {
                    RemoveStack(StageCamera.main);
                }

                AddStack(StageCamera.main);
            }
        }

        private static void SetOverlay(Camera camera, UniversalAdditionalCameraData stageCameraData = null)
        {
            if (stageCameraData == null)
            {
                stageCameraData = camera.GetUniversalAdditionalCameraData();
            }

            if (stageCameraData != null)
            {
                stageCameraData.renderType = CameraRenderType.Overlay;
            }
        }

        public static void AddStack(Camera overlayCamera)
        {
            if (!MainCameraData.cameraStack.Contains(overlayCamera)) // 防止重复添加
            {
                SetOverlay(overlayCamera);
                MainCameraData.cameraStack.Add(overlayCamera);
            }

            if (overlayCamera != StageCamera.main)
            {
                FixUICamera();
            }
        }

        public static void RemoveStack(Camera overlayCamera)
        {
            if (MainCameraData.cameraStack.Contains(overlayCamera))
            {
                MainCameraData.cameraStack.Remove(overlayCamera);
            }
        }
    }
}