#include <iostream>
#include <vector>
#include "ezSockets.h"
#include <conio.h>

/*
MAJOR NOTES ABOUT EZSOCKETS:
	You CANNOT use a copy constructor or an equals operator on ezSockets!
	They will fail!  This is to prevent orphaned sockets.  You must keep
	them as pointers if you need to move them around (ie in servers)

  You may find more information about this library in the future on CNLohr.net
*/

int main()
{
	ezSockets G;

	//Example 1: HTTP Transaction
	G.Create();	//default, TCP, stream
	G.mode = ezSockets::skGeneral;
	G.bBlocking = true;
	if( G.Connect( "www.google.com", 80 ) )
	{
		cout<<"Connection to www.google.com OK"<<endl;
		G.WriteLine( "GET / HTTP/1.1" );
		G.WriteLine( "Host: www.google.com" );
		G.WriteLine( "User-Agent: ezSockets demo program\r\n\r\n" );

		string s;
		while (	G.ReadLine( s ) )
		{
			cout<<s<<endl;
			if( s.length() == 0 )
				break;
		}
	} else
		cout<<"Failed connection to Google.com"<<endl;
	G.Close();

	//Example 2: UDP Broadcast
	ezSockets UDPBroadcast;
	ezSockets UDPReceive;

	UDPBroadcast.mode = ezSockets::skUDP;
	UDPBroadcast.bBlocking = true;
	UDPBroadcast.Create( IPPROTO_UDP, SOCK_DGRAM );

	UDPReceive.mode = ezSockets::skUDP;
	UDPReceive.bBlocking = true;
	UDPReceive.Create( IPPROTO_UDP, SOCK_DGRAM );

	if( !UDPReceive.Bind( 8665 ) )
		cout<<"Failed to bind to local port."<<endl;
	if( !UDPBroadcast.Connect( "255.255.255.255", 8665 ) )
		cout<<"Failed to bind to broadcast port."<<endl;

	ezSocketsPacket pOutPack;
	pOutPack.ClearPacket();
	pOutPack.Write1( 54 );
	pOutPack.Write2( 595 );
	pOutPack.Write4( 525600 );
	pOutPack.WriteNT( "YAY!" );
	pOutPack.Write2( 2 );
	UDPBroadcast.SendPack( pOutPack );
	
	Sleep(100);

	ezSocketsPacket pInPack;
	if( UDPReceive.ReadPack( pInPack ) )
	{
		cout<<"Sender's IP Address:"<<
			( pInPack.PositionTAG )%256<<'.'<<
			( pInPack.PositionTAG >> 8 )%256<<'.'<<
			( pInPack.PositionTAG >> 16 )%256<<'.'<<
			( pInPack.PositionTAG >> 24 )%256<<endl;
		cout<<"Original packet size (from packet system):"<<(int)pInPack.Read4()<<endl;
		cout<<(int)pInPack.Read1()<<endl;
		cout<<(int)pInPack.Read2()<<endl;
		cout<<(int)pInPack.Read4()<<endl;
		cout<<pInPack.ReadNT()<<endl;
		cout<<(int)pInPack.Read2()<<endl;
		cout<<endl;
	} else
		cout<<"Failed to receive broadcast."<<endl;
	UDPBroadcast.Close();
	UDPReceive.Close();

	//Example 3, an HTTP server!
	ezSockets ServerSocket;
	ServerSocket.Create();
	ServerSocket.Bind(80);
	ServerSocket.Listen();

	if( !ServerSocket.Check() )
	{
		cout<<"Failed to make working server socket."<<endl;
		return -1;
	}
	
	vector< ezSockets * > vClients;

	ServerSocket.bBlocking = false;
	ServerSocket.mode = ezSockets::skGeneral;

	cout<<"Server running.  Visit http://127.0.0.1 in a web browser.  Press any key to stop."<<endl;
	while( !kbhit() )
	{
		if( ServerSocket.CanRead() )
		{
			//We have an incomming connection.
			ezSockets * NewClient = ServerSocket.Accept();

			//It worked!
			if( NewClient->Check() )
			{
				cout<<"Connection established from:"<<NewClient->GetAddress()<<endl;
				NewClient->mode = ezSockets::skGeneral;
				NewClient->bBlocking = false;
				vClients.push_back( NewClient );
			}
		}

		for( unsigned i = 0; i < vClients.size(); i++ )
		{
			if( vClients[i]->IsError() || !vClients[i]->Check() )
			{
				cout<<"Connection dropped."<<endl;
				vClients[i]->Close();
				delete vClients[i];
				vClients.erase( vClients.begin() + i );
				i--;
				continue;
			}
			if( vClients[i]->CanRead() )
			{
				ezSockets * ThisSocket = vClients[i];
				string sLine;
				while( ThisSocket->ReadLine( sLine ) )
				{
					cout<<sLine<<endl;
					if( sLine.empty() )
					{
						ThisSocket->WriteLine( "HTTP/1.1 200 Ok" );
						ThisSocket->WriteLine( "Content-Length: 11" );
						ThisSocket->WriteLine( "Content-Type: text/plain" );
						ThisSocket->WriteLine( "Connection: close" );
						ThisSocket->WriteLine( "" );
						ThisSocket->WriteLine( "Hello World" );
						ThisSocket->Close();
						cout<<"sent."<<endl;
					}
				}
			}
		}
		Sleep(20);
	}


	return 0;
}


/* 
 * (c) 2006 Charles Lohr
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, and/or sell copies of the Software, and to permit persons to
 * whom the Software is furnished to do so, provided that the above
 * copyright notice(s) and this permission notice appear in all copies of
 * the Software and that both the above copyright notice(s) and this
 * permission notice appear in supporting documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
 * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
 * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
 * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */
