using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Variables;

public class MonsterController : MonoBehaviour, IResettable
{

    [SerializeField, Header("References")]
    Reference<float> m_light;

    [SerializeField]
    private GameObject[] m_possibleFrames;


    [SerializeField]
    private Transform m_player;


    [SerializeField]
    public GameObject m_defaultObject;

    private void OnEnable()
    {
        m_light.OnValueChanged += OnLightChange;
    }

    private void OnDisable()
    {
        m_light.OnValueChanged -= OnLightChange;
    }

    private void Start()
    {
        foreach (Transform child in transform)
        {
            if (child.gameObject.activeInHierarchy)
                m_defaultObject = child.gameObject;
        }
    }



    private void ChangeRandomMonster()
    {
        GameObject[] inactiveFrames = m_possibleFrames.Where(p => !p.activeInHierarchy).ToArray();
        GameObject nextFrame = inactiveFrames[Random.Range(0, inactiveFrames.Length)];
        
        foreach(Transform child in transform)
        {
            child.gameObject.SetActive(child.gameObject == nextFrame);
        }
    }


    private void OnLightChange(float value)
    {
        if (value <= 0)
        {
            ChangeRandomMonster();
        }

    }

    public void OnLevelLoad()
    {

    }

    public IEnumerator OnResetStart(float time)
    {
        yield break;
    }

    public void OnResetEnd()
    {
        foreach (Transform child in transform)
        {
            child.gameObject.SetActive(child.gameObject == m_defaultObject);
        }
    }
}
