using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }
    public GameObject toothPrefab, candyPrefab;
    public Transform[] holes;
    public Transform candySpawnpoint;
    public float maxSpawnDistance, minCandySpawnTime, maxCandySpawnTime;
    public UnityEvent winEvent;
    int activeTeeth;

    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        activeTeeth = holes.Length;
        for (int i = 0; i < holes.Length; i++)
        {
            Enemy t = Instantiate(toothPrefab, new Vector3(
                Random.Range(transform.position.x-maxSpawnDistance, transform.position.x + maxSpawnDistance), 
                toothPrefab.transform.position.y, 
                Random.Range(transform.position.z-maxSpawnDistance, transform.position.z+maxSpawnDistance)), 
                Quaternion.identity).GetComponent<Enemy>();

            t.targetHole = holes[i];
            holes[i].GetComponent<ToothHole>().assignedTooth = t;
        }

        StartCoroutine(CandySpawnLoop());
    }

    public void ToothReachedHole()
    {
        activeTeeth--;
        if(activeTeeth <= 0)
        {
            Win();
        }
    }

    void Win()
    {
        winEvent.Invoke();
    }

    public void ToothFreedFromHole()
    {
        activeTeeth++;
    }

    IEnumerator CandySpawnLoop()
    {
        while(activeTeeth > 0)
        {
            yield return new WaitForSeconds(Random.Range(minCandySpawnTime, maxCandySpawnTime));
            Instantiate(candyPrefab, candySpawnpoint.position, Quaternion.identity);
        }
    }
}
