using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public interface IRoundCallback
{
    void OnRoundStart();
    void OnRoundEnd();
}

public class RoundController : MonoBehaviour, IFighterCallback
{

    public static RoundController instance { get; private set; }

    public List<IRoundCallback> roundCallbacks = new List<IRoundCallback>();
    public bool roundRunning { get; private set; }

    [SerializeField, Tooltip("After the last Fighter of a type died, how many seconds to wait until ending the current round")]
    float restartDelayAfterLastFighterDeath = 3f;

    BaseCameraController cameraController;
    int aliveEnemiesCount = 0;

    public void StartRound()
    {
        if (roundRunning)
        {
            return;
        }
        roundRunning = true;
        SetGameSpeed(1f);
        roundCallbacks.ForEach(c => c.OnRoundStart());

        aliveEnemiesCount = 0;
        // Fighters clear their callbacks every round end
        GameObject.FindGameObjectWithTag("AntiPlayer").GetComponent<Fighter>().callbacks.Add(this);
        foreach (GameObject f in GameObject.FindGameObjectsWithTag("Enemy"))
        {
            f.GetComponent<Fighter>().callbacks.Add(this);
            aliveEnemiesCount++;
        }
    }

    public void StopRound()
    {
        if (!roundRunning)
        {
            return;
        }
        roundRunning = false;
        SetGameSpeed(1f);
        roundCallbacks.ForEach(c => c.OnRoundEnd());
    }

    public void ToggleRound()
    {
        if (roundRunning)
        {
            StopRound();
        }
        else
        {
            StartRound();
        }
    }

    public void SetGameSpeed(float multiplier)
    {
        Time.timeScale = multiplier;
    }

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
        DontDestroyOnLoad(gameObject);

        cameraController = Camera.main.GetComponent<BaseCameraController>();
    }

    public void OnFighterDeath(Fighter fighter)
    {
        var isAntiPlayer = fighter.CompareTag("AntiPlayer");
        if (!isAntiPlayer)
        {
            aliveEnemiesCount--;
        }
        if (isAntiPlayer || aliveEnemiesCount == 0)
        {
            // Slowmo-zoom to last dying Figher
            var targetGameSpeed = 0.2f;
            SetGameSpeed(targetGameSpeed);
            cameraController.AnimateToPosition(fighter.transform.position + new Vector3(0f, 0.75f), 1.5f, 0.125f * targetGameSpeed);
            Invoke(nameof(StopRoundAfterDeath), targetGameSpeed * restartDelayAfterLastFighterDeath);
        }
    }

    void StopRoundAfterDeath()
    {
        StopRound();
        cameraController.AnimateToPosition(new Vector3(0, 0, 0), 5f, 0.15f);
    }

}