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

public class Decor : MonoBehaviour, IEventGameOver
{
    [Serializable]
    internal struct Collectible
    {
        internal List<GameObject> m_collectibles;
    }

    [SerializeField] internal List<Collectible> m_hiddenCollectibles;

    private float m_currentAlpha = 1f;
    private bool m_isDead;
    protected SpriteRenderer[] m_spriteRenderers;

    public bool IsDead { get { return m_isDead; } }

    protected virtual void Start()
    {
        ExecuteEvents.AddHandler<IEventGameOver>(this);        

        if (m_hiddenCollectibles.Count > 0)
        {
            Collectible collectible = m_hiddenCollectibles[UnityEngine.Random.Range(0, m_hiddenCollectibles.Count)];
            for (int index = 0; index < collectible.m_collectibles.Count; ++index)
            {
                collectible.m_collectibles[index].SetActive(true);
            }
        }        
    }

    protected virtual void OnDestroy()
    {
        ExecuteEvents.RemoveHandler<IEventGameOver>(this);
    }

    protected virtual void Update()
    {
        if (m_isDead)
        {
            m_currentAlpha -= Time.deltaTime;

            for (int index = 0; index < m_spriteRenderers.Length; ++index)
            {
                Color color = m_spriteRenderers[index].color;
                color.a = m_currentAlpha;
                m_spriteRenderers[index].color = color;

                if (m_currentAlpha <= 0f)
                {
                    Destroy(gameObject);
                }
            }            
        }
    }

    public virtual void OnGameOver()
    {
        m_isDead = true;
        m_spriteRenderers = GetComponentsInChildren<SpriteRenderer>();
    }
}
