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

public class CameraManager : MonoBehaviour
{
    public CameraData data;
    private List<EntityController> players = new List<EntityController>();
    public Vector3 additivePosition = Vector3.zero;
    [HideInInspector] public UIController UI;

    private Camera cam;
    private List<AudioSource> sources = new List<AudioSource>();

    public void Awake()
    {
        additivePosition = Vector3.right * data.initialPosition;
        players = FindObjectsOfType<EntityController>().Where((e) => e.gameObject.tag == "Player").ToList();
        UI = Instantiate(data.UI).GetComponentInChildren<UIController>();

        sources = GetComponentsInChildren<AudioSource>().Where((s) => s.clip == null).ToList();
        cam = GetComponent<Camera>();
    }

    public bool IsOutOfBounds(Vector3 v3)
    {
        Vector3 boundsLeft = cam.ScreenToWorldPoint(Vector3.zero);
        return v3.x <= boundsLeft.x;
    }

    public void Update()
    {
        additivePosition += Vector3.right * data.gameplaySideSpeed * Time.deltaTime;

        Vector3 totalPos = Vector3.zero;

        if (totalPos.x < additivePosition.x)
        {
            totalPos.x = additivePosition.x;
        }

        totalPos.y = transform.position.y;
        totalPos.z = transform.position.z;

        Vector3 finalPos = totalPos;

        transform.position = Vector3.MoveTowards(transform.position, finalPos, data.cameraLerpSpeed * Time.deltaTime);
    }

    private int lastSoundIndex = 0;
    public void PlaySound(AudioClip clip)
    {
        AudioSource source = sources[lastSoundIndex]; //  sources.FirstOrDefault((s) => s.clip == null);
        if (source != null)
        {
            source.clip = clip;
            source.volume = 0.5f;
            source.pitch = Random.Range(-1.0f, 2.0f);
            source.Play();
        }

        lastSoundIndex++;
        if (lastSoundIndex >= sources.Count) lastSoundIndex = 0;
    }
}
