using System;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using UnityEngine.InputSystem;

public class CameraControls : MonoBehaviour
{
    public int CurrentCameraIndex { get; private set; } = 1;

    [SerializeField] private InputActionAsset _playerControls = default;
    [SerializeField] private List<CinemachineVirtualCamera> _cameras = new List<CinemachineVirtualCamera>();

    private InputAction camera1Input = default;
    private InputAction camera2Input = default;
    private InputAction camera3Input = default;
    private InputAction camera4Input = default;
    private InputAction camera5Input = default;

    // Start is called before the first frame update
    void Start()
    {
        var playerControlsActionMap = _playerControls.FindActionMap("Player");
        camera1Input = playerControlsActionMap.FindAction("Camera1");
        camera2Input = playerControlsActionMap.FindAction("Camera2");
        camera3Input = playerControlsActionMap.FindAction("Camera3");
        camera4Input = playerControlsActionMap.FindAction("Camera4");
        camera5Input = playerControlsActionMap.FindAction("Camera5");

        camera1Input.performed += ActivateCamera(1);
        camera2Input.performed += ActivateCamera(2);
        camera3Input.performed += ActivateCamera(3);
        camera4Input.performed += ActivateCamera(4);
        camera5Input.performed += ActivateCamera(5);
    }

    public void ChangeCamera(int cameraNumber)
    {
        CurrentCameraIndex = cameraNumber;
        CinemachineVirtualCamera vCam;
        foreach (var cvc in _cameras)
        {
            if (cvc != null)
            {
                cvc.enabled = false;
            }
        }
        vCam = _cameras[cameraNumber - 1];
        vCam.enabled = true;
    }

    private Action<InputAction.CallbackContext> ActivateCamera(int cameraNumber)
    {
        if (cameraNumber <= _cameras.Count)
        {
            return (InputAction.CallbackContext context) =>
            {
                ChangeCamera(cameraNumber);
            };
        }
        return context => { };
    }
}
