using UnityEngine;
using ExposeProperty;

public class Room : MonoBehaviour {

    public AbsoluteZone zone;

    public GameObject hider;

    private WaveLevels waveLevels;

    [ExposeProperty]
    public int X
    {
        get
        {
            return zone.x;
        }
        set
        {
            zone.x = value;
            UpdateTransform();
        }
    }

    [ExposeProperty]
    public int Y
    {
        get
        {
            return zone.y;
        }
        set
        {
            zone.y = value;
            UpdateTransform();
        }
    }

    public void UpdateTransform()
    {
        transform.position = new Vector3(zone.x * Griddy.Instance.cellWidth, zone.y * Griddy.Instance.cellHeight, transform.position.z);
    }

    public void UpdatePositionOnGrid()
    {
        zone.x = (int)(transform.position.x / Griddy.Instance.cellWidth);
        zone.y = (int)(transform.position.y / Griddy.Instance.cellHeight);
        UpdateTransform();
    }

    void Awake()
    {
        waveLevels = new WaveLevels();
    }

    void Start()
    {
        SetHidden(true);
        UpdatePositionOnGrid();
    }

    public void UpdateWaveLevels()
    {
        int cellCount = zone.width * zone.height;

        waveLevels = new WaveLevels();

        for (int i = zone.MinX; i <= zone.MaxX; i++)
        {
            for (int j = zone.MinY; j <= zone.MaxY; j++)
            {
                WaveLevels cellLevels = Griddy.Instance.GetCell(i, j).WaveLevels;
                foreach(WaveType key in cellLevels.levels.Keys)
                {
                    if(cellLevels.GetWaveLevel(key) > 0)
                    {
                        waveLevels.ChangeWaveLevel(key, 1);
                    }
                }
                //waveLevels.Increase(Grid.Instance.GetCell(i, j).WaveLevels);
            }
        }

        Attackable[] attackables = GetComponentsInChildren<Attackable>();

        bool hidden = true;
        foreach(WaveType key in waveLevels.levels.Keys)
        {
            if(waveLevels.GetWaveLevel(key) >= cellCount/2)
            {
                hidden = false;
                foreach (Attackable attackable in attackables)
                {
                    attackable.Attack(waveLevels);
                }
            }
        }
        SetHidden(hidden);
    }

    public void SetHidden(bool hidden)
    {
        if (hider != null)
        {
            hider.SetActive(hidden);
        }
    }

}
