using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.Types;

public class Server : MonoBehaviour {

	List<int> connections;
	List<string> IPs;
	List<int> ports;

	int hostID;
	int selfChannelID;

	// Use this for initialization
	void Start () {
		connections = new List<int>();
		IPs = new List<string>();
		ports = new List<int>();

		NetworkTransport.Init();
		ConnectionConfig config = new ConnectionConfig();
		selfChannelID  = config.AddChannel(QosType.ReliableSequenced);
		HostTopology topology = new HostTopology(config, 10);
		hostID = NetworkTransport.AddHost(topology, 49610);

		//bidon
		/*connections.Add(-1);
		IPs.Add("YOLO");
		ports.Add(1);*/

	}
	
	// Update is called once per frame
	void Update () {
		int recHostID; 
		int connectionID; 
		int channelID; 
		byte[] recBuffer = new byte[1024]; 
		int bufferSize = 1024;
		int dataSize;
		byte error;
		NetworkEventType recData = NetworkTransport.Receive(out recHostID, out connectionID, out channelID, recBuffer, bufferSize, out dataSize, out error);
		switch (recData)
		{
			case NetworkEventType.ConnectEvent:

				int port;
				string ip;

				NetworkID networkID;
				NodeID nodeID;

				NetworkTransport.GetConnectionInfo(recHostID, connectionID, out ip, out port, out networkID, out nodeID, out error);

				ip = ip.Remove(0, 7); //remove ::ffff:

				Debug.Log("Connection from " + ip + ":" + port);
			break;
				
			case NetworkEventType.DataEvent:
				Buffer inputBuffer = new Buffer(recBuffer);

				int code = inputBuffer.readInt();

				switch(code) {
					case 0:
						string message = inputBuffer.readString();

						Debug.Log(message);

					break;
					case 2:
						bool isServer = inputBuffer.readBool();

						if (isServer) {
							NetworkTransport.GetConnectionInfo(recHostID, connectionID, out ip, out port, out networkID, out nodeID, out error);

							ip = ip.Remove(0, 7); //remove ::ffff:

							connections.Add(connectionID);
							IPs.Add(ip);
							ports.Add(port);
						}
						else {
							for (int i = 0; i < connections.Count; i++) {

								Buffer buffer = new Buffer();
								buffer.writeInt(1);
								buffer.writeString(IPs[i]);
								buffer.writeInt(ports[i]);

								NetworkTransport.Send(hostID, connectionID, channelID, buffer.getArray(), buffer.getLength(), out error);
							}
						}

					break;
				}
			break;
		}
	}
}
