/* Copyright (c) 2008-2011 - Eric P. Mangold
 * Released under the terms of the MIT/X11 license - see LICENSE.txt */
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace Benchmarks
{
    class EmptyCommand: AMP.Command
    {
        public EmptyCommand()
            : base("EmptyCommand")
        {}
    }

    class bench
    {
        static AMP.Command cmd;
        static int port;
        static TcpListener listener;

        static void Main(string[] args)
        {
            cmd = new EmptyCommand();
            
            listener = new TcpListener(0);
            listener.Start(5);

            port = ((IPEndPoint)listener.LocalEndpoint).Port;
            
            Console.WriteLine("Listening on port {0}", port);

            var s = new Thread(Server);
            s.Start();

            Client();
        }

        static void Server()
        {
            TcpClient client;
            AMP.Protocol protocol;

            // the AMP.Command's we're going to respond to
            while (true)
            {
                client = listener.AcceptTcpClient();
                protocol = new AMP.Protocol(client.GetStream());

                // we could also pass a 'state' argument to RegisterResponder
                // which becomes the 'state' argument in the responders (below).
                // Since we aren't passing anything, then state will always be null
                protocol.RegisterResponder(cmd, handleCmd);
                protocol.StartReading(); // start the async data-reading loop
            }
        }

        static Object handleCmd(AMP.Msg msg, Object state)
        {
            return new AMP.Msg {};
        }

        static void Client()
        {
            var client = new TcpClient("localhost", port);
            var protocol = new AMP.Protocol(client.GetStream());
            protocol.StartReading(); // start the async data-reading loop

            int block = 10000;
            int count = 0;
            var start = DateTime.Now;
            double howLong;
            var msg = new AMP.Msg { };
            while (true)
            {
                protocol.CallRemote(cmd, msg);
                count++;

                if (count == block)
                {
                    count = 0;
                    howLong = (DateTime.Now - start).TotalSeconds;
                    System.Console.WriteLine("{0:0} AMP/s", block / howLong);
                    start = DateTime.Now;
                }
            }
        }
    }
}
