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

public class TopSocketController : MonoBehaviour {

    public static TopSocketController instance;

    public List<TopSocket> topSockets = new List<TopSocket>();

    void Awake ()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this);
        }
    }

    public static void addSocket (TopSocket socketToAdd)
    {
        if (instance == null)
        {
            return;
        }
        if (!instance.topSockets.Contains(socketToAdd))
        {
            instance.topSockets.Add(socketToAdd);
        }
    }

    public static void removeSocket (TopSocket socketToRemove)
    {
        if (instance == null)
        {
            return;
        }
        if (instance.topSockets.Contains(socketToRemove))
        {
            instance.topSockets.Remove(socketToRemove);
        }
    }

    public void setCallReceived (SocketChannelSettings channelToReceiveCall, float lengthOfCall)
    {
        TopSocket socketToReceive = topSockets [Random.Range(0, topSockets.Count)];
        while (socketToReceive.currentState > TopSocket.TopSocketState.pluggedInIdle)
        {
            socketToReceive = topSockets [Random.Range(0, topSockets.Count)];
        }
        StartCoroutine(RunCallReceivedRoutine(socketToReceive, channelToReceiveCall, lengthOfCall));
    }

    IEnumerator RunCallReceivedRoutine (TopSocket socketToReceiveCall, SocketChannelSettings channelToReceive, float lengthOfCall)
    {
        socketToReceiveCall.setChannel(channelToReceive);
        float timeCallReceived = Time.time;
        while (Time.time - timeCallReceived < lengthOfCall)
        {
            yield return null;
        }
        socketToReceiveCall.setChannel(null);
    }

    public void ClearAllSockets ()
    {
        for (int i = 0; i < topSockets.Count; i++)
        {
            TopSocket socketToClear = topSockets [i];
            socketToClear.clearSocket();
        }
        StopAllCoroutines();
    }
}
