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

public class SocketController : MonoBehaviour {

    public static SocketController instance;

    public List<Socket> availableSockets = new List<Socket>();

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

    public static void AddSocket (Socket socketToAdd)
    {
        if (instance == null)
        {
            return;
        }
        if (!instance.availableSockets.Contains(socketToAdd))
        {
            instance.availableSockets.Add(socketToAdd);
        }
    }

    public static void RemoveSocket (Socket socketToAdd)
    {
        if (instance == null)
        {
            return;
        }
        if (instance.availableSockets.Contains(socketToAdd))
        {
            instance.availableSockets.Remove(socketToAdd);
        }
    }
    
    public void FillRandomAvailSocketWithCableOfChannel (SocketChannelSettings channel, CableSettings cableSettings)
    {
        Socket socketToFill = availableSockets [Random.Range(0, availableSockets.Count)];
        while (socketToFill.socketFilled)
        {
            socketToFill = availableSockets [Random.Range(0, availableSockets.Count)];
        }
        socketToFill.FillSocketWithCable(channel, cableSettings);
    }

    public void FillSocketsFromAvailable (Dictionary<SocketChannelSettings, int> availableChannels)
    {
        foreach (SocketChannelSettings channel in availableChannels.Keys)
        {
            for (int i = 0; i < availableChannels [channel]; i++)
            {
                FillRandomAvailSocketWithCableOfChannel(channel, HayWiresSettings.cableManager.defaultCable);
            }
        }
    }

    public void ClearAllSockets ()
    {
        for (int i = 0; i < availableSockets.Count; i++)
        {
            Socket socketToClear = availableSockets [i];
            if (socketToClear.socketFilled)
            {
                socketToClear.ClearSocket();
            }
        }
    }
}
