
#include "game.h"

//#include "Packet.h"
//#include <iostream>
 bool done2=false ;
extern int ms = 0;
int initAll()
{
	allegro_init();
	install_keyboard();
	install_timer();
	install_mouse();

text_mode(-1);
//graphic = true;


	
	

	// install a MIDI sound driver 
if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) 
	{
		return 1;
	}
	////////////////////##### i put this in for fullsreen F2 togoll

	set_color_depth(24);
	if (set_gfx_mode(GFX_AUTODETECT_WINDOWED,640,480,0,0)!=0)
	{
		return -1;
	}
set_display_switch_mode(SWITCH_BACKGROUND); //allows game to run in back ground

	/*
  BITMAP *buffer;


    buffer=create_bitmap(SCREEN_W,SCREEN_H);
	*/













	return 0;
}

//BITMAP *buffer;



int pass =0;

void printErrorExit(BITMAP *bm)
{
    NLenum err = nlGetError();
    
    if(err == NL_SYSTEM_ERROR)
    {
		//textout(screen,font,"Piccolo",100,200,makecol(0,255,0));
		textprintf_centre(bm, font, 40, 176, makecol(255, 255, 255),"System error: %s\n", nlGetSystemErrorStr(nlGetSystemError()));
       // printf("System error: %s\n", nlGetSystemErrorStr(nlGetSystemError()));
    }
    else
    {
        textprintf_centre(bm, font, 40, 186, makecol(255, 255, 255),"HawkNL error: %s\n", nlGetErrorStr(err));
    }
    nlShutdown();
    exit(1);
}

#define MAX_CLIENTS 1
NLenum socktype = NL_TCP_PACKETS;
NLushort serverport = 25000;
NLsocket    sock[MAX_CLIENTS];
    NLaddress   addr;
    NLint       i, count = 4;
	NLbyte		str[256];

enum EVENT {START,AWAITLOOKUP,AWAITCONNECTION,CONNECTED,
AWAITDATA,SENDDATA,ERROREXIT,FINISH,NULLEVENT};


EVENT State = START;



bool Start()
{

//	cout << "starting" << endl;

//make client sokect

	i =0;
	sock[i] = nlOpen(0, socktype);
	if(sock[i] == NL_INVALID)
	{
		printf(" client: nlOpen error\n ");
	sleep(5);
		State = START;
//		cout << " reStarting "<< endl;
		sleep(3);
		return true; //Mite need to chaing this to get a loop
	}


//	cout << " client sokect has been made " << endl;
	State = AWAITLOOKUP;
	return true;
}



bool Awaitlookup()
{
//	cout << "finding address " <<endl;
	//setting string to pointer

	nlStringToAddr(serverIP.c_str(),&addr);
	 
	nlSetAddrPort(&addr, serverport);
//	cout << " connection address set " <<endl;

	State = AWAITCONNECTION;
	return true;
}


bool Awaitconnection()
{


//	cout <<" tring to connect"<<endl;
	
	string nums[2] ;

rest(1);

	if(!nlConnect(sock[i], &addr))
	{
		
			printf(" client: nlConnect error\n ");
			sleep(1);
//			cout << "tring to connect again " << endl;
			State = START;
			return true;
		
	}

	logontrys=0;
//		cout<<" waiting for server to say im connected" <<endl;
		while (!nlListen(sock[i])) // let's listen on this socket 

			{

				while(nlRead(sock[i], str, sizeof(str)) > 0)
					 {

						for (int i=0, j=0;i< sizeof(str);i++)
						{
							if(str[i] != '|')
							{
								nums[j] += str[i];
							}
							else if(str[i] == '|')
							{
								j++;
							}
						

						}
						netId = StringToNumber(nums[0]);
						csock = StringToNumber(nums[1]);

						computerId  = StringToNumber(nums[0]);
//						cout <<" nlREading "<< endl ;
				
//						cout << str << endl;
							//  printf("\"%s\",", str);
							pass = 1;

					}	

				if (pass == 1)
					{
						ms = 3; ///start game grafics
						//waiting for server to say im connected
						State = CONNECTED;
						//State = SENDDATA; //rigged for test
						pass = 0;
						return true;
					}
				

			}

				if(pass == 0)
				{
					logontrys++;

					if(logontrys<1)
						{	

							printf(" client: nlConnect error\n ");
						State = AWAITCONNECTION;
						return true;
					}
					else
					{
						textprintf(screen, font, 250, 220, makecol(255, 255, 255),"can not find server:");
						sleep(2);
						done2=false ;
						State = START;
						ms = 0; 

						return true;
					}
				}	
	
	//return true; 
	//textprintf(screen, font, 250, 220, makecol(255, 255, 255),"can not find server:");
return true;

			
		
		
	
}

bool Connected()
{
	int nub = 0;
//	cout <<"connected "<<endl;

//	cout << "press 1 for State = SENDDATA" <<endl;
//	cout << "press 2 for State = AWAITDATA" <<endl;


//outboxbuffer += "0|"+NumberToString(netId)+"|007|karen,newton,karen,namackan,female,2060,1590,32,32,3,0,0,0,1,4,4,1,"+NumberToString(netId)+",0`~"; //login
//outboxbuffer += "0|"+NumberToString(netId)+"|006|"+NumberToString(netId)+","+NumberToString(csock)+",piccolosun,newton`~"; //login
//outboxbuffer += "0|"+NumberToString(netId)+"|004|none`~";
//outboxbuffer += "0|"+NumberToString(netId)+"|001|King Piccolo,namackan,female,2060,1590,32,32,3,0,0,0,1,4,4,1,"+NumberToString(netId)+",0`~";

//outboxbuffer +=	"0001|0002|001|ghgh,dfhg,hjh,2060,1584,32,32,3,0,0,0,1,4,4,1,5`~";
//cin >> nub;
State = SENDDATA; //rigged for test
	if (nub == 1)
		{
		State = SENDDATA;
		}

	 if (nub == 2)
		{
		State = AWAITDATA;
		}

	return true;
}

bool Senddata()
{
//	cout << " geting data ready for send " <<endl;

	//sprintf(str, " king piccolo ", i);
//cin >> str;

//str = "0001|0002|001|ghgh,dfhg,hjh,2060,1494,32,32,3,32,32,0,1,4,4,1,5`~";
//	cout << " sending on sockect " <<endl;
	if (outboxbuffer.length() > 0)
	{
	textprintf(screen, font, 100, 10, makecol(255, 255, 255),outboxbuffer.c_str());
//Sleep(5000);
		Packet newpacket;
		string p = newpacket.send();
		nlWrite(sock[i],p.c_str() , p.length()+1);
	}
//	nlWrite(sock[i], "0001|0002|001|ghgh,dfhg,hjh,2060,1494,32,32,3,32,32,0,1,4,4,1,5`~", strlen("0001|0002|001|ghgh,dfhg,hjh,2060,1494,32,32,3,32,32,0,1,4,4,1,5`~") + 1); 
////some in her to say check outbox to see if anything needs sending

	
	
	
	
	




State = AWAITDATA;//rigged for test
//State = SENDDATA; //rigged for test
//	State = CONNECTED;
	//State = SENDDATA;
	return true;
}


bool Awaitdata()
{
	if (pass==0)
	{
//	cout << " Lising on sockect " <<endl;
	pass = 1;
	}
	if(nlListen(sock[i]))// let's listen on this socket 
		{
			
		
        State = AWAITDATA;
		}


		while(nlRead(sock[i], str, sizeof(str)) > 0)
            {
//				cout <<" nlREading"<< endl;
                printf("\"%s\",", str);
				inboxbuffer += str;
				if (pass == 1)
				{
				
				pass = 0;
				}
//str[127] = 0; // null terminate the char string

            }

//	State = FINISH;

 

	State = SENDDATA;
	//State = AWAITDATA;
	return true;
}




bool CloseErrorexit()
{
//	cout << "error "<<endl;
	return true;
}

bool Finsh()
{
//	cout << "finshed closing sockect"<<endl;
	return true;
}

///////////////////////////////////////	
 volatile int speed_counter = 0;

      void increment_speed_counter()
      {
         speed_counter++;
      }

      END_OF_FUNCTION(increment_speed_counter)
/////////////////////////////////////////////////////////////

int main(int argc, char **argv)
{

	if (initAll()<0) return 0;



	Client client = Client();
	//bool done=false;
	Game newgame;


	//newgame.play_song(MIDI_BEAT);
	/////////////////////////////////////////////////networing
	    NLenum          type = NL_IP; //default network type 
	    if(!nlInit())
        printErrorExit(screen);
    
    //textprintf_centre(Layergrid, font, 250, 276, makecol(255, 255, 255),"nlGetString(NL_VERSION) = %s\n\n", nlGetString(NL_VERSION));
   // textprintf_centre(Layergrid, font, 250, 286, makecol(255, 255, 255),"nlGetString(NL_NETWORK_TYPES) = %s\n\n", nlGetString(NL_NETWORK_TYPES));
    if (argc == 2)
    {
        if(strcmp(argv[1], "NL_IPX") == 0)
        {
            type = NL_IPX;
        }
        else if(strcmp(argv[1], "NL_LOOP_BACK") == 0)
        {
            type = NL_LOOP_BACK;
        }
    }

    if(!nlSelectNetwork(type))
        printErrorExit(screen);
//put menu here

bool bcontinue = true;

////////////////////////////////////
LOCK_VARIABLE(speed_counter);
         LOCK_FUNCTION(increment_speed_counter);

         install_int_ex(increment_speed_counter, BPS_TO_TIMER(60));
//////////////////////////////////////////////////////
	while (done==false)
	{
	//rest(1)	; //take 100%cpu or runs slow	

		if( ms == 3||ms == 0 ||done2 == true ) //menu stuff done?
		{
			
			blit((BITMAP*)newgame.data[BACK].dat,newgame.get_views()[0].get_buffer(),0,0,0,0,640,480);
			if (ms == 3)
			{
				
				outboxbuffer += "0|"+NumberToString(netId)+"|004|none`~";
				outboxbuffer += "0|"+NumberToString(netId)+"|006|"+NumberToString(netId)+","+NumberToString(csock)+","+username+","+password+"`~"; 
				username = " "; //clear username
				password = " "; //clear password
				done2 = false;
				ms = 4;
			}
			else
			{
				ms = draw_login(newgame.get_views()[0].get_buffer());
				rest(1)	; //take 100%cpu or runs slow
			if ( ms == -1)
			{
				done = true;
				//exit the hole game
			}
			
			
			
			
			}

			
			


			blitBuffer(newgame.get_views()[0].get_buffer());
			
		}
		
		if ( ms > 0)
		{

			//do
			//{

			switch(State)
			{

				case START:
				bcontinue = Start();
				break;

				case AWAITLOOKUP:
				bcontinue = Awaitlookup();
				break;

				case AWAITCONNECTION:
				bcontinue = Awaitconnection();
				break;
				case CONNECTED:
			
				bcontinue =Connected();
				break;

				case SENDDATA:
				bcontinue = Senddata();
				break;

				case AWAITDATA:
				bcontinue = Awaitdata();
				break;

				case ERROREXIT:
				bcontinue =	CloseErrorexit();
				break;

				case FINISH:
				Finsh();
				bcontinue = false;
				break;
			}
		}
	//}while(bcontinue);

		if( ms == 4)
		{
	

			 //htThreadSleep(0);
			
		//	blit((BITMAP*)newgame.data[BACK].dat,newgame.get_views()[0].get_buffer(),0,0,0,0,640,480);

			//clear_to_color(newgame.views[0].buffer,2);

			//newgame.do_game_networking();
if (speed_counter > 0) 
{
	if (key[KEY_F12])
	{
		outboxbuffer += "0|"+NumberToString(netId)+"|010|"+NumberToString(netId)+","+NumberToString(csock)+","+username+","+password+"`~"; 
			

	}
       newgame.do_game_logic();

        speed_counter--;
}
	if(graphic != false)
	{       
		newgame.do_game_gfx();     
	}

 //acquire_screen();
			
//release_screen();

			
			
		}			
		
	}
	nlShutdown();
	return 0;
}
END_OF_MAIN();



/*


	LOCK_VARIABLE(timer);
	LOCK_FUNCTION(inc_timer);

 	install_int(inc_timer,1000);

volatile int timer=1;

void inc_timer(void)
{
    if (!game_pause)
    {
        timer++;
    }
}
END_OF_FUNCTION(inc_timer);
*/