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 GameObject associatedChest;

    public void Start()
    {

    }

    public void Update()
    {
        if(associatedChest == null)
        {
            associatedChest = GameObject.FindGameObjectWithTag("ChestCollection").transform.Find("Prize Chest")?.gameObject;

            if(associatedChest != null)
                associatedChest.GetComponent<ChestWrapper>().Lock();
        }


        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);
            } else
            {
                Debug.Log(Counter);
                coroutine = SpownWithDelay(0.5f);
            }

            StartCoroutine(coroutine);
        }

        if (Counter <= 0 && killedMinions >= 30)
            associatedChest.GetComponent<ChestWrapper>().Unlock();

    }

    // 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

        GameObject spownerObject = null;

        do
        {
            spownerObject = respownPoints
                .ElementAt(UnityEngine.Random.Range(0, respownPoints.Count()));
        } while (spownerObject.GetComponent<MinionRespowner>().Blocked == true);

        // Spawn object
        spownerObject.GetComponent<MinionRespowner>().Respown(minion);
    }

}