using UnityEngine;
using UnityEngine.Events;

public class Attackable : MonoBehaviour {

    public WaveType waveType;

    public int minLevel = 1;

    public UnityEvent onAttacked;

    public bool active;

    public int moneyGain;

    public bool IsSensibleTo(WaveType waveType)
    {
        return waveType == this.waveType;
    }

    public void Attack(WaveLevels waveLevels)
    {
        /*foreach(WaveType key in waveLevels.levels.Keys)
        {
            if(waveLevels.GetWaveLevel(key) > 0)
            {
                Attack(key);
            }
        }*/
        if(waveLevels.GetWaveLevel(waveType) > minLevel)
        {
            Attack();
        }
    }

    /*public void Attack(WaveType waveType)
    {
        if(waveType == this.waveType)
        {
            Attack();
        }
    }*/

    public void Attack()
    {
        if (!active)
        {
            active = true;
            onAttacked.Invoke();
            Level.Instance.Money += moneyGain;

            //Launch attack with delay
            WaveSource waveSource = GetComponent<WaveSource>();
            if (waveSource != null)
            {
                Invoke("AddWaveSourceToLevel", Level.Instance.attackDelay);
            }

            AudioSource audioSource = GetComponent<AudioSource>();
            if(audioSource != null)
            {
                audioSource.Play();
            }
            else
            {
                audioSource = transform.parent.GetComponent<AudioSource>();
                if(audioSource != null)
                {
                    audioSource.Play();
                }
            }
        }
    }

    void AddWaveSourceToLevel()
    {
        /*WaveSource waveSource = Instantiate(GetComponent<WaveSource>());
        waveSource.position = new Vector2I(
            waveSource.position.x + (int)(transform.position.x / Griddy.Instance.cellWidth),
            waveSource.position.y + (int)(transform.position.y / Griddy.Instance.cellHeight)
        );*/

        Level.Instance.AddWave(GetComponent<WaveSource>());
    }

}
