using NUnit.Framework;
using System.Collections.Generic;
using Unity.Cinemachine;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.SceneManagement;

public class CameraManager : MonoBehaviour
{
    [SerializeField] private List<CameraRigBase> _cameraRigList; 
    private CameraRigBase _currentCameraRig; //현재 활성화된 플레이어의 카메라 묶음 조종객체

    private float minFOV = 40f;
    private float maxFOV = 100f;

    private void Awake()
    {


    }

    private void Start()
    {
        _ = InitializeCameraRig();
    }

    private void Update()
    {

    }

    private async Awaitable InitializeCameraRig()
    {
        CinemachineBrain brain = Camera.main.GetComponent<CinemachineBrain>();

        while (brain.ActiveVirtualCamera == null)
        {
            await Awaitable.NextFrameAsync();
        }

        // 가져오는게 실제 cinemachine카메라가 아니라 매니저일수도 있기에 MonoBehaviour로 변환후 찾기
        if (brain.ActiveVirtualCamera is MonoBehaviour activeComponent) 
        {
            _currentCameraRig = activeComponent.GetComponentInParent<CameraRigBase>();
        }
    }

    public void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {

    }

    public void SetCameraRig(CameraRigBase cameraRig)
    {
        foreach(CameraRigBase crb in _cameraRigList)
        {
            crb.Priority = 10;
        }
        
        _currentCameraRig = cameraRig;
        _currentCameraRig.Priority = 15;

    }

    public CinemachineCamera GetLiveCinemachineCamera()
    {
        return _currentCameraRig.LiveCmCamera;
    }

    public void ZoomCamera(float offset)
    {
        if (_currentCameraRig is AimCameraRig rig)
        {
            rig.CurrentFOV = Mathf.Clamp(rig.CurrentFOV - offset, minFOV, maxFOV);
        }
    }


    public Vector3 GetViewportPointToRayEndPoint(Vector3 vpPoint,float rayLength)
    {
        Ray ray = Camera.main.ViewportPointToRay(vpPoint);
        return ray.GetPoint(rayLength);
    }
}
