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

public class SwitchesAndExit : MonoBehaviour
{
    List<ExitSwitch> m_Switches;
    int m_NumSwitches;
    int m_NumActivatedSwitches;
    Vector3 m_StartingGatePosition;
    private float m_CurrentTime;
    private ExitGateController m_ExitGateSpriteController;

    public GameObject m_SwitchesContainer;
    public GameObject m_Exit;

    void Awake()
    {
        m_Switches = new List<ExitSwitch>();
        int allPoints = m_SwitchesContainer.transform.childCount;
        for (int i = 0; i < allPoints; i++)
        {
            m_Switches.Add(m_SwitchesContainer.transform.GetChild(i).GetComponent<ExitSwitch>());
        }
        m_NumSwitches = allPoints;
        m_NumActivatedSwitches = 0;

        m_ExitGateSpriteController = m_Exit.GetComponentInChildren<ExitGateController>();
        m_ExitGateSpriteController.SetOpen(false);
    }

    // Use this for initialization
    void Start ()
    {
		
	}
	
	// Update is called once per frame
	void Update ()
    {
		
	}

    public void SetIsTriggered(GameObject aGameObject)
    {
        m_NumActivatedSwitches++;
        if (IsCompletelyTriggered())
        {
            m_ExitGateSpriteController.SetOpen(true);
        }
    }

    public void SetIsNotTriggered(GameObject aGameObject)
    {
        m_NumActivatedSwitches--;
        if (!IsCompletelyTriggered())
        {
            m_ExitGateSpriteController.SetOpen(false);
        }
    }

    public bool IsCompletelyTriggered()
    {
        return m_NumActivatedSwitches == m_NumSwitches;
    }

    public void EndLevel()
    {
        if (IsCompletelyTriggered())
        {
            int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
            if (SceneManager.GetSceneByBuildIndex(currentSceneIndex) != null)
            {
                SceneManager.LoadScene(currentSceneIndex + 1);
            }
            else
            {
                SceneManager.LoadScene(0);
            }
        }
    }
}
