using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using System.Collections;

class CounterRespowner : MonoBehaviour
{
    public const string RESPOWNER_NAME = "DungeonRespowner";

    public bool Respown = true;

    public int Counter = 20;

    public List<GameObject> minions;

    public List<GameObject> respownPoints;

    public int killedMinions = 0;

    private IEnumerator coroutine;


    public void Start()
    {
    }

    public void Update()
    {
        if(Respown && Counter > 0)
        {
            Respown = false;

            if (killedMinions < 4 && Counter > 20)
            {
                coroutine = SpownWithDelay(1.5f);
            } else if(Counter <= 20 && killedMinions >= 4)
            {
                coroutine = SpownWithDelay(3.0f);
            }

            StartCoroutine(coroutine);

        }
    }

    // najpier 10
    // a potem w wiekszych dstepach kolejne 20
    private IEnumerator SpownWithDelay(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);

        RespownMinion();

        Counter -= 1;
        Respown = true;
    }

    public void RespownMinion()
    {
        GameObject minion = null;
        Vector3 spowner = Vector3.zero;

        // Draw minion
        minion = minions
            .ElementAt(UnityEngine.Random.Range(0, minions.Count()))
        ;

        // Decide which spowner use
        spowner = respownPoints
            .ElementAt(UnityEngine.Random.Range(0, respownPoints.Count()))
            .transform
            .position
        ;

        // Change position
        var newPosition = new Vector3(
            spowner.x + UnityEngine.Random.Range(-3.8f, 3.8f), 
            spowner.y + UnityEngine.Random.Range(-3.8f, 3.8f),
            10
        );

        BuildMinion(minion, newPosition);
    }

    public void BuildMinion(GameObject minion, Vector3 coord)
    {
        var sceneGui = GameObject.FindGameObjectWithTag("EnemyCollection");

        if (sceneGui == null)
        {
            throw new Exception("GUI not found on scene!!!");
            return;
        }

        var newMinion = GameObject.Instantiate(minion, coord, Quaternion.identity, sceneGui.transform);

        newMinion.name = minion.name;
       // newMinion.transform.SetParent(sceneGui.transform);

        newMinion.GetComponent<SpriteRenderer>().sortingOrder = 3;

        newMinion.AddComponent<RespownTrigger>();
        newMinion.GetComponent<RespownTrigger>().SetParentRespowner(gameObject);

    }
}