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

namespace Assets._game.scripts
{
    public class CameraManager : Singleton<CameraManager>
    {

        [SerializeField]
        private Cinemachine.CinemachineTargetGroup _targetGroup;

        [SerializeField] private GameObject _battleCameraRig;

        public void CreateGameCameraRig()
        {
            var rig = Instantiate(_battleCameraRig);
            _targetGroup = rig.GetComponentInChildren<CinemachineTargetGroup>();
        }

        public void AddTarget(Transform player)
        {
            Debug.Log("Adding player", player);
            //_targetGroup.
            var targets = _targetGroup.m_Targets;
            bool wasAdded = false;
            for (int i = 0; i < targets.Length; i++)
            {
                var target = targets[i];
                if (target.target != null)
                {
                    continue;
                }

                target.target = player;
                targets[i] = target;
                wasAdded = true;
                break;
            }

            if (!wasAdded)
            {
                //Add additional raget
                var targetList = targets.ToList();
                targetList.Add(new CinemachineTargetGroup.Target()
                {
                    target = player,
                    radius = 1,
                    weight = 1
                });
                targets = targetList.ToArray();
            }
            _targetGroup.m_Targets = targets;
        }

        public void RemoveTarget(Transform player)
        {
            if (_targetGroup.IsEmpty)
            {
                return;
            }

            var targets = new List<CinemachineTargetGroup.Target>(_targetGroup.m_Targets);

            var target = targets.FirstOrDefault(t => t.target == player);


            if (target.target != null)
            {
                targets.Remove(target);
            }

            _targetGroup.m_Targets = targets.ToArray();
        }


    }
}
