using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    [SerializeField] private GameEventListener_PhotonView onPlayerSpawned;
    [Space]
    public bool SpectatorMode = false;
    public bool SmoothMovement = false;
    [SerializeField] private Vector3 offset;
    [SerializeField] private Vector3 rotationEuler;

    public List<GameObject> players = new List<GameObject>();

    private float zDistance;
    private GameObject firstInRace;

    private Vector3 startingPos;
    private Quaternion startingRot;



    private void Awake()
    {
        startingPos = this.transform.position;
        startingRot = this.transform.rotation;
        onPlayerSpawned.Response.AddListener(OnPlayerSpawned);
    }

    // Update is called once per frame
    void Update()
    {
        if (SpectatorMode)
        {
            zDistance = 0f;
            for (int i = players.Count - 1; i >= 0; i--)
            {
                if (players[i] == null)
                {
                    players.RemoveAt(i);
                    continue;
                }

                if (players[i].transform.position.z - this.transform.position.z > zDistance)
                {
                    zDistance = players[i].transform.position.z - this.transform.position.z;
                    firstInRace = players[i];
                }
            }
        }
        if (firstInRace == null) return;
        if (SmoothMovement)
            this.transform.position = Vector3.Lerp(this.transform.position, firstInRace.transform.position + offset, Time.deltaTime);
        else
            this.transform.position = firstInRace.transform.position + offset;
        this.transform.rotation = Quaternion.Euler(rotationEuler);
    }

    public void OnPlayerSpawned(PhotonView photonView)
    {
        players.Add(photonView.gameObject);

        if (SpectatorMode) return;
        if (!photonView.Owner.IsLocal) return;

        firstInRace = photonView.gameObject;
    }
}
