using UnityEngine;

public class CrackManager : MonoBehaviour
{
    public RectTransform spawnArea; // the image / panel
    public GameObject crackPrefab;
    public GameObject tv;
    public int crackCount = 5;

    private int remaining;
    private bool stillAlive = false;

    void OnEnable()
    {
        if (!stillAlive)
        {
            SpawnCracks();
            stillAlive = true;
        }
    }

    void SpawnCracks()
    {
        remaining = crackCount;

        for (int i = 0; i < crackCount; i++)
        {
            GameObject crack = Instantiate(crackPrefab, spawnArea);

            RectTransform rt = crack.GetComponent<RectTransform>();
            rt.anchoredPosition = RandomPointInRect(spawnArea);

            crack.GetComponent<Crack>().Init(this);
        }
    }

    public void CrackDestroyed()
    {
        remaining--;

        if(remaining <= 0)
        {
            stillAlive = false;
            if (tv)
            {
                tv.GetComponent<TvHandler>().CloseMiniGame(true);
            }
        }
    }


    Vector2 RandomPointInRect(RectTransform rect)
    {
        Vector2 size = rect.rect.size;
        return new Vector2(
            Random.Range(-size.x / 2f, size.x / 2f),
            Random.Range(-size.y / 2f, size.y / 2f)
        );
    }

}
