using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CorgiLabs.Utility;
using UnityEngine.Experimental.Rendering.LWRP;

public class PowerGenerator : GhostEventSource, ITriggerable
{
    [SerializeField] private byte m_SequenceLength = 4;
    [SerializeField] private Light2D[] m_FeedbackLights = new Light2D[4];

    [SerializeField] private Color m_PressedColor = Color.yellow;
    [SerializeField] private Color m_WrongColor = Color.red;
    [SerializeField] private Color m_SuccessColor = Color.green;

    [SerializeField] private float m_ResetDelay = 1f;

    private List<byte> m_Sequence = new List<byte>();

    private AudioSource m_AudioSource;

    private int m_SequenceIndex;

    private void Awake()
    {
        m_AudioSource = GetComponent<AudioSource>();
    }

    protected override void Start()
    {
        base.Start();

        for (byte i = 0; i < m_SequenceLength; i++)
            m_Sequence.Add(i);

        m_SequenceIndex = m_SequenceLength;

        StartEvent();
    }


    public override void StartEvent()
    {
        base.StartEvent();

        ShuffleSequence();
        ResetAttempt();
        ServiceLocator.Get<GhostSpawner>().SpawnAt(transform.position);

        m_AudioSource.Stop();
    }

    public void Trigger(byte switchId)
    {
        if (m_SequenceIndex < m_SequenceLength)
        {
            if (switchId == m_Sequence[m_SequenceIndex])
            {
                m_FeedbackLights[switchId].color = m_PressedColor;
                m_FeedbackLights[switchId].enabled = true;

                m_SequenceIndex++;

                if (m_SequenceIndex == m_SequenceLength)
                {
                    foreach (Light2D light in m_FeedbackLights)
                        light.color = m_SuccessColor;

                    m_AudioSource.Play();

                    EventManager.TriggerEvent<GhostEventSource>(EventID.GhostEventSuccess, this);
                }
            }
            else if (m_SequenceIndex > 0)
            {
                m_SequenceIndex = m_SequenceLength;

                foreach (Light2D light in m_FeedbackLights)
                    light.color = m_WrongColor;

                Invoke("ResetAttempt", m_ResetDelay);
            }

        }
    }

    private void ShuffleSequence()
    {
        List<byte> tempSequence = new List<byte>(m_Sequence.ToArray());

        m_Sequence.Clear();

        int el;

        while(tempSequence.Count > 0)
        {
            el = Random.Range(0, tempSequence.Count);
            m_Sequence.Add(tempSequence[el]);
            tempSequence.RemoveAt(el);
        }
    }

    private void ResetAttempt()
    {
        m_SequenceIndex = 0;

        foreach(Light2D light in m_FeedbackLights)
            light.enabled = false;
    }
}
