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

public class SwitchesAndGate : MonoBehaviour
{
    List<GateSwitch> m_Switches;
    int m_NumSwitches;
    int m_NumActivatedSwitches;
    bool m_MoveGate = false;
    Vector3 m_StartingGatePosition;
    private float m_CurrentTime;

    public GameObject m_EndGatePosition;
    public GameObject m_SwitchesContainer;
    public GameObject m_Gate;
    public float m_TimeToPointS = 1.0f;

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

    // Use this for initialization
    void Start ()
    {
		
	}

    private void Update()
    {
        if (m_MoveGate)
        {
            m_CurrentTime -= Time.deltaTime;
            if (m_CurrentTime <= 0)
            {
                m_CurrentTime = 0.0f;
                m_MoveGate = false;
            }

            bool isCompletelyTriggered = IsCompletelyTriggered();
            Vector3 startingPoint = isCompletelyTriggered ? m_StartingGatePosition : m_EndGatePosition.transform.position;
            Vector3 endingPoint = !isCompletelyTriggered ? m_StartingGatePosition : m_EndGatePosition.transform.position;

            float percentageThere = Vector3.Distance(m_StartingGatePosition, m_Gate.transform.position) / Vector3.Distance(m_StartingGatePosition, m_EndGatePosition.transform.position);
            
            Vector3 nextPos = Vector2.Lerp(startingPoint, endingPoint, (m_TimeToPointS - m_CurrentTime) / m_TimeToPointS);
            m_Gate.transform.position = nextPos;
        }
    }

    public void SetIsTriggered(GameObject aGameObject)
    {
        m_NumActivatedSwitches++;
        if(IsCompletelyTriggered())
        {
            m_MoveGate = true;
            m_CurrentTime = m_TimeToPointS;
        }
    }

    public void SetIsNotTriggered(GameObject aGameObject)
    {
        m_NumActivatedSwitches--;
        if (!IsCompletelyTriggered())
        {
            m_MoveGate = true;
            m_CurrentTime = m_TimeToPointS;
        }
    }

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