using MoreMountains.Tools;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;

public class CameraStackManager : MonoBehaviour
{
    public bool overrideMainCamera = false;

    static List<Camera> cameras = new List<Camera>();
    public static Camera mainCamera = null;

    new Camera camera;

    private void Start()
    {
        camera = GetComponent<Camera>();
        cameras.Add(camera);
        if (mainCamera == null || overrideMainCamera) {
            mainCamera = camera;
            OverlayCanvas.instance.WorldCamera = mainCamera;
        }
        SetupMainCamera();
    }

    private void OnDestroy()
    {
        cameras.Remove(camera);
        if (mainCamera == camera && cameras.Count > 0) {
            mainCamera = cameras[0];
            OverlayCanvas.instance.WorldCamera = mainCamera;
        }
        SetupMainCamera();
    }

    private void SetupMainCamera()
    {
        mainCamera.gameObject.GetComponent<AudioListener>().enabled = true;
        UniversalAdditionalCameraData cameraData = mainCamera.GetUniversalAdditionalCameraData();
        cameraData.renderType = CameraRenderType.Base;
        cameraData.cameraStack.Clear();
        for (int i = 0; i < cameras.Count; i++) {
            Camera cam = cameras[i];
            if (mainCamera != cam) {
                cam.gameObject.GetComponent<AudioListener>().enabled = false;
                cam.GetUniversalAdditionalCameraData().renderType = CameraRenderType.Overlay;
                cameraData.cameraStack.Add(cam);
            }
        }
    }
}
