//To run echotest.exe:
//MONO_PATH+=<A directory which contains WebSocket.dll> mono ./echotest.exe
using System;
using System.Net;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
public class MainClass
{
	public static void Main()
	{
		var server = new WebSocketServer(20080);
		server.OnClientConnected += OnClientConnected;
		Console.WriteLine("Started.");
		var debug_out = new TextWriterTraceListener(Console.Out);
		Trace.Listeners.Add(debug_out);
		Debug.WriteLine("DEBUG");
		server.Run();
	}

	//クライアントの一覧・IPアドレスを保管するDictionary.
	//The dictionary to store clients and their ipaddresses.
	private static Dictionary<WebSocketClient,IPEndPoint> client_dictionary = new Dictionary<WebSocketClient,IPEndPoint>();

	private static void OnClientConnected(object sender,ClientConnectedEventArgs e)
	{
		Console.WriteLine("Client [{0}] connected.",((IPEndPoint)e.Client.Socket.RemoteEndPoint).ToString());
		e.Client.OnMessageReceived += OnMessageReceived;
		e.Client.OnClientDisconnected += OnClientDisconnected;

		client_dictionary.Add(e.Client,(IPEndPoint)e.Client.Socket.RemoteEndPoint);
	}

	private static void OnMessageReceived(object sender,MessageReceivedEventArgs e)
	{
		var client = (WebSocketClient)sender;
		Console.WriteLine("Received by [{0}]",((IPEndPoint)client.Socket.RemoteEndPoint).ToString());

		var received_msg = Encoding.UTF8.GetString(e.DecodedMessage);
		Console.WriteLine("Received message: {0}",received_msg);
		
		var msg = new WebSocketMessage();
		msg.Append(received_msg);

		client.SendMessage(msg);
	}

	public static void OnClientDisconnected(object sender,ClientDisconnectedEventArgs e)
	{
		var client = (WebSocketClient) sender;

		//client.Socket.RemoteEndPointはアクセスできない(ソケットは閉じられている)ため、
		//各自でIPEndPointを保管する必要がある。
		//Because client.Socket.RemoteEndPoint is inaccecible,
		//you need to store IPEndPoint yourself.
		var ipendpoint = client_dictionary[client];
		Console.WriteLine("Client [{0}] disconnected.",ipendpoint.ToString());
	}


}
