/****************************************************************************
	Aplikace pro zprostredkovani pripojeni k PC a predani rizeni vyssim
	aplikacim (konzole, plocha).


	POZOR:	k portu se automaticky pridava predpona 10, tudiz pokud je zadan
			25, znamena to 1025. pokud zadam 132, znamena to 10132.

*****************************************************************************/

#ifdef PCSIM
	#include "stdafx.h"
#endif

#include "Applications.h"
#include "GRAPHICS.h"
#include "OS.h"
#include "GLCD.h"
#include "Drivers.h"
/****************************************************************************
	Definicni makro pro osetreni cekani na zpracovani prikazu

*****************************************************************************/
#define CONNECTOR_WAIT_FOR_RESULT() if (WifiBusy() == YES)\
                                  {\
                                    LedOff(LED_4);\
                                    protectStamp = GetTimeStamp(); \
                                    break;\
                                  }\
                                  if (WifiOK() == NO)\
                                  {\
                                    remoteState = OS_STATE_ERROR;\
                                    DebugOut("ERROR\r\n");\
                                    break;\
                                  }\
                                  connectionHandleStamp = GetTimeStamp();\
                                  if (GetElapsedTime(protectStamp) < 100)\
                                    break;\
                                  LedOff(LED_4);

TScreen connectorScreen;														//Obrazovka aplikace
TScreenObject connectorScreenObjects[CONNECTOR_OBJECT_COUNT];					//Pole objektu aplikace

/****************************************************************************
	Definice pisem pro aplikaci

*****************************************************************************/
FONT connectorButtonsEnabledFont = {RGB_DARK_GREEN,FONT_SMALL,RGB_LIGHT_GRAY};
FONT connectorScreenFont = {RGB_CYAN,FONT_SMALL,RGB_DARK_GRAY};

/****************************************************************************
	definice parametru grafickych objektu

*****************************************************************************/
TScreenObjectParams connectorMainShapeParams = {CONNECTOR_XC-CONNECTOR_XA,CONNECTOR_YC-CONNECTOR_YA,&connectorScreenFont};
TScreenObjectParams connectorLongButtonsParams = {CONNECTOR_BUTTONS_WIDTH, CONNECTOR_BUTTONS_HEIGHT, &connectorButtonsEnabledFont};
TScreenObjectParams connectorSmallButtonsParams = {CONNECTOR_BUTTONS_WIDTH/2-CONNECTOR_BUTTONS_DISTANCE/2, CONNECTOR_BUTTONS_HEIGHT, &connectorButtonsEnabledFont};
TScreenObjectParams connectorSpecialButtonsParams = {CONNECTOR_BUTTONS_WIDTH/2-CONNECTOR_BUTTONS_DISTANCE/2, CONNECTOR_BUTTONS_HEIGHT-5, &connectorButtonsEnabledFont};

TApplicationInternal ConnectorInternal;										//Ridici objekt aplikace
int ConnectorResult = -1;													//Vysledkova promenna
extern WIFI_STATE wifiState;
static unsigned char commandBuffer[30];										//zasobnik na prikazy pro wifi
TIME_STAMP connectionHandleStamp;											//znamka pro mereni intervalu behem pripojeni
CONNECTOR_OBJECT startingObject;											//Startovaci objekt
		
char ipRemote[] = "NNN.NNN.NNN.NNN:NN ";									//Vzdalena IP adresa a port - text tlacitka

unsigned char remoteIP[20] = "192.168.0.100";								//Vzdalena IP adresa
unsigned char remotePort[3] = "25";											//vzdaleny port
OS_TYPE remoteOS = OS_WINDOWS;												//System, ke kteremu se pripojuji				
OS_CONTROL remoteControl = OS_TOUCHPAD;										//Rezim pripojeni
OS_CONNECT remoteConnection = OS_WIFI;										//Zpusob pripojeni
OS_STATE remoteState = OS_STATE_DISC;										//Stav pripojeni
ANSWER remoteSSL = NO;														//Sifrovani
TIME_STAMP disconnectStamp;													//Cas pro vyprseni platnosti prikazu


/****************************************************************************
	Postovni schranka aplikace

	Vstup: 
		msg:			Zprava pro aplikaci

	Vystup
		RESULT:			Vysledek operace

*****************************************************************************/
RESULT CNMsgBox(MESSAGE * msg)
{
	POSITION* tmpPosition = 0;
	switch (msg->msg)
	{
	case RUN:
		DebugOut("Connector RUN command received.\n");
		if (ConnectorInternal.State == CONNECTOR_READY)									//Pokud je aplikace zinicializovana
		{
			ConnectorResult = -1;														//Vynuluj vysledek
			ConnectorInternal.State = CONNECTOR_RESTART;								//Prejdi do stavu pro spusteni
			return PASSED;
                        
		}
		DebugOut("Connector could not be run.\n");
		return FAILED;
			
		break;
	case INIT:
		if (ConnectorInternal.State == CONNECTOR_NOT_INITIALIZED)						//Pokud je aplikace nezinicializovana
		{
			DebugOut("Connector INIT command received.\n");
			ConnectorInternal.State = CONNECTOR_INITIALIZE;								//Proved inicializaci
			return PASSED;		
		}
		break;
	case GET_STATE:
		return (RESULT)ConnectorInternal.State;											//Vraci stav aplikace
		break;
	case GET_RESULT:
		return (RESULT)ConnectorResult;													//Vraci vysledek po ukonceni aplikace
		break;
	case APP_CLICK:
		ConnectorInternal.ClickPosition.isFresh = YES;									//pokud bylo prijato kliknuti pro aplikaci
		tmpPosition = (POSITION*)msg->data;												//Uloz data pro zpracovani
		ConnectorInternal.ClickPosition.x = tmpPosition->x;
		ConnectorInternal.ClickPosition.y = tmpPosition->y;
		DebugOut("Connector click received.\n");
		return PASSED;
		break;
	default:
		break;
		
	}
	return FAILED;
}

/****************************************************************************
	Odezva tlacitka pro konfiguraci IP adresy

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorIPConfigCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
#ifdef FIX_ALL_WARNINGS
	obj;message;
#endif
	if (remoteConnection != OS_WIFI)										//Pokud neni pripojeni pres wifi, nic nedelej
		return;
	MESSAGE ipMask = {SET_MASK,ipRemote};									//jinak posli klavesnici masku
	if (SendTaskMessage(KEYBOARD,&ipMask) == FAILED || SendTaskMessage(KEYBOARD,&DEFAULT_MSG_NUMERIC_ONLY) == FAILED)
	{
		DebugOut("Keyboard configuration failed.\n");
		return;		
	}
	else
	{
		startingObject = (CONNECTOR_OBJECT) obj->id;						//Nastav spousteci objekt
		ConnectorInternal.RunApplication(KEYBOARD);							//Spust klavesnici
	}

}

/****************************************************************************
	Odezva tlacitka Sifrovani

	Vstup: 
		obj:			Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorCipherButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
	if (remoteConnection != OS_WIFI)				//Pokud neni pripojeni  pres wifi			
		return;
	if (remoteSSL == YES)							//prepinani sifrovani (ano/ne)
		remoteSSL = NO;
	else
		remoteSSL = YES;
	obj->draw(obj,message);							//Aktualizace objektu
}

/****************************************************************************
	Odezva tlacitka pro volbu OS

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorOSButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
	if (remoteOS == OS_WINDOWS)						//Prepinani windows/linux
	{
		remoteOS = OS_LINUX;
		remoteControl = OS_CONSOLE;
	}
	else
	{
		remoteOS = OS_WINDOWS;
		remoteControl = OS_DESKTOP;
	}
	obj->draw(obj,message);							//Aktualizace objektu+aktualizace rezimu spojeni
	ConnectorInternal.Screen->objects[CONNECTOR_REMOTE_MODE].draw(&ConnectorInternal.Screen->objects[CONNECTOR_REMOTE_MODE],message);
}

/****************************************************************************
	Odezva tlacitka pro volbu rezimu spojeni

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorModeButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
	if (remoteOS == OS_WINDOWS)							//Pokud je windows
	{
		if (remoteControl == OS_DESKTOP)				//pokud je plocha
			remoteControl = OS_TOUCHPAD;				//touchpad
		else
			remoteControl = OS_DESKTOP;					//plocha
	}
	else
	{
		remoteControl = OS_CONSOLE;						//Konzole
	}
	obj->draw(obj,message);								//Prekresleni
}

/****************************************************************************
	Odezva tlacitka Zpet

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorBackButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
#ifdef FIX_ALL_WARNINGS
	obj;message;
#endif
	ConnectorInternal.State = CONNECTOR_STOP;			//Ukonci aplikaci
}

/****************************************************************************
	Odezva tlacitka Pripojit

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorConnectButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
#ifdef FIX_ALL_WARNINGS
	obj;message;
#endif

	ConnectorInternal.State = CONNECTOR_CONNECTING;					//Prejdi do stavu Pripojovani
    remoteState = OS_STATE_DISC;									//Nastav stav wifi Odpojen
	connectorScreen.DisableAllObjects();							//Zakazani vsech objektu
	connectorScreen.objects[CONNECTOR_BACK].state = OBJECT_ENABLED;	//Povoleni tlacitka zpet
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_CIPHERING);	//Prekresleni
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_IP_ADDRESS);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_CONNECT);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_TYPE);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_REMOTE_MODE);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_REMOTE_OS);
	connectionHandleStamp = GetTimeStamp();							//Casova znamka

}

/****************************************************************************
	Odezva tlacitka pro volbu rozhrani

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorTypeButtonCallback(TScreenObject* obj ,OBJECT_MESSAGE message)
{
#ifdef FIX_ALL_WARNINGS
	obj;message;
#endif
	switch(remoteConnection)					//Podle aktualniho stavu urci dalsi
	{
	case OS_WIFI:
		remoteConnection = OS_SERIAL;
		break;
	case OS_SERIAL:
		remoteConnection = OS_USB;
		break;
	case OS_USB:
		remoteConnection = OS_WIFI;
		break;
	default:
		remoteConnection = OS_WIFI;
		break;
	}
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_CIPHERING);		//Aktualizuj objekty
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_IP_ADDRESS);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_CONNECT);
	ConnectorInternal.Screen->UpdateObject(CONNECTOR_TYPE);
	
}

/****************************************************************************
	Funkce pro kresleni datovych tlacitek

	Vstup: 
		obj:				Instance objektu
		message:			Zprava pro aplikaci

	Vystup
		neni

*****************************************************************************/
void connectorDataButtonDraw(TScreenObject* obj ,OBJECT_MESSAGE message)
{
	DrawButtonShape(obj,message);								//Vykresleni tvaru tlacitek
	LCD_Goto_XY(obj->x+12,obj->y-2);							//presun pro tisk
	LCD_Set_Font(obj->params->font);							//Nastaveni fontu
	LCD_Set_Font_Size(FONT_MINIMAL);							//Nastaveni maleho fontu
	LCD_printf(obj->caption);									//tisk hlavicky
	LCD_Goto_XY(obj->x+12,obj->y+18);							//Presun pro tisk dat
	LCD_Set_Font(&connectorButtonsEnabledFont);					//Nastaveni fontu
	
	//POkud probiha pripojovani
	if (ConnectorInternal.State == CONNECTOR_CONNECTING || ConnectorInternal.State == CONNECTOR_DISCONNECT)
	{
		LCD_Set_Font_Color(RGB_DARK_GRAY);				//Zesedni
	}
	

	switch(obj->id)										//Podle ID objektu tiskni prislusna data
	{
	case CONNECTOR_IP_ADDRESS:
		if (remoteConnection != OS_WIFI)
			LCD_Set_Font_Color(RGB_DARK_GRAY);
		LCD_Goto_XY(obj->x+6,obj->y+18);
		LCD_printf(remoteIP);
		LCD_putchar(':');
		LCD_printf(remotePort);
		break;
	case CONNECTOR_REMOTE_OS:
		if (remoteOS == OS_LINUX)
			LCD_printf(STR_OS_LINUX);
		else
			LCD_printf(STR_OS_WINDOWS);
		break;
	case CONNECTOR_REMOTE_MODE:
		switch(remoteControl)
		{
		case OS_CONSOLE:
			LCD_printf(STR_MODE_CONSOLE);
			break;
		case OS_TOUCHPAD:
			LCD_printf(STR_MODE_TOUCHPAD);
			break;
		case OS_DESKTOP:
			LCD_printf(STR_MODE_DESKTOP);
			break;
		}
		break;
	case CONNECTOR_TYPE:
		switch (remoteConnection)
		{
		case OS_WIFI:
			LCD_printf(STR_WIFI);
			break;
		case OS_USB:
			LCD_printf(STR_USB);
			break;
		case OS_SERIAL:
			LCD_printf(STR_SERIAL);
			break;
		}
		break;
	case CONNECTOR_CIPHERING:
		if (remoteConnection != OS_WIFI)
			LCD_Set_Font_Color(RGB_DARK_GRAY);
		if (remoteSSL == NO)
		{
			LCD_printf(STR_NO);
		}
		else
			LCD_printf(STR_YES);
		break;
	}
}


/****************************************************************************
	Funkce pro inicializaci aplikace

	Vstup: 
		neni

	Vystup
		RESULT:		Vysledek operace

*****************************************************************************/
RESULT ConnectorInitialize(void)
{
	connectorScreen.Init(CONNECTOR_OBJECT_COUNT,connectorScreenObjects,&connectorScreenFont,NO);					//Inicializace obrazovky

	ConnectorInternal.Init(CONNECTOR,CONNECTOR_XA,CONNECTOR_YA,CONNECTOR_XC,CONNECTOR_YC,&connectorScreen,0,YES);	//Inicializace ridici struktury
	if (ConnectorInternal.Screen == 0)
	{
		return FAILED;
	}

	/****************************************************************************
		Inicializace grafickych objektu

	*****************************************************************************/
	ConnectorInternal.Screen->objects[CONNECTOR_MAIN_SHAPE].Init(	CONNECTOR_XA,
																CONNECTOR_YA,
																BACKGROUND,
																CONNECTOR_MAIN_SHAPE,
																STR_CONNECTOR_CAPTION,
																OBJECT_ENABLED,
																&connectorMainShapeParams,
																0,
																&DrawTextBox);

		ConnectorInternal.Screen->objects[CONNECTOR_TYPE].Init(			CONNECTOR_BUTTONS_LEFT+CONNECTOR_XA,
																CONNECTOR_BUTTONS_TOP+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_TYPE,
																STR_TYPE,
																OBJECT_ENABLED,
																&connectorSmallButtonsParams,
																&connectorTypeButtonCallback,
																&connectorDataButtonDraw);

	ConnectorInternal.Screen->objects[CONNECTOR_IP_ADDRESS].Init(		CONNECTOR_BUTTONS_LEFT+CONNECTOR_XA,
																CONNECTOR_BUTTONS_TOP+CONNECTOR_BUTTONS_HEIGHT+CONNECTOR_BUTTONS_DISTANCE+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_IP_ADDRESS,
																STR_IP_ADDRESS,
																OBJECT_ENABLED,
																&connectorLongButtonsParams,
																&connectorIPConfigCallback,
																&connectorDataButtonDraw);

	ConnectorInternal.Screen->objects[CONNECTOR_CIPHERING].Init(			CONNECTOR_BUTTONS_LEFT+CONNECTOR_BUTTONS_WIDTH/2+CONNECTOR_XA+CONNECTOR_BUTTONS_DISTANCE/2,
																CONNECTOR_BUTTONS_TOP+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_CIPHERING,
																STR_CONNECTOR_CIPHERING,
																OBJECT_ENABLED,
																&connectorSmallButtonsParams,
																&connectorCipherButtonCallback,
																&connectorDataButtonDraw);

	ConnectorInternal.Screen->objects[CONNECTOR_REMOTE_OS].Init(			CONNECTOR_BUTTONS_LEFT+CONNECTOR_XA,
																CONNECTOR_BUTTONS_TOP+2*(CONNECTOR_BUTTONS_HEIGHT+CONNECTOR_BUTTONS_DISTANCE)+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_REMOTE_OS,
																STR_CONNECTOR_OS,
																OBJECT_ENABLED,
																&connectorSmallButtonsParams,
																&connectorOSButtonCallback,
																&connectorDataButtonDraw);

	ConnectorInternal.Screen->objects[CONNECTOR_REMOTE_MODE].Init(		CONNECTOR_BUTTONS_LEFT+CONNECTOR_BUTTONS_WIDTH/2+CONNECTOR_XA+CONNECTOR_BUTTONS_DISTANCE/2,
																CONNECTOR_BUTTONS_TOP+2*(CONNECTOR_BUTTONS_HEIGHT+CONNECTOR_BUTTONS_DISTANCE)+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_REMOTE_MODE,
																STR_CONNECTOR_MODE,
																OBJECT_ENABLED,
																&connectorSmallButtonsParams,
																connectorModeButtonCallback,
																&connectorDataButtonDraw);

	ConnectorInternal.Screen->objects[CONNECTOR_CONNECT].Init(			CONNECTOR_BUTTONS_LEFT+CONNECTOR_XA,
																CONNECTOR_BUTTONS_TOP+3*(CONNECTOR_BUTTONS_HEIGHT+CONNECTOR_BUTTONS_DISTANCE)+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_CONNECT,
																STR_CONNECT,
																OBJECT_ENABLED,
																&connectorSpecialButtonsParams,
																&connectorConnectButtonCallback,
																&DrawButton);

	ConnectorInternal.Screen->objects[CONNECTOR_BACK].Init(				CONNECTOR_BUTTONS_LEFT+CONNECTOR_BUTTONS_WIDTH/2+CONNECTOR_XA+CONNECTOR_BUTTONS_DISTANCE/2,
																CONNECTOR_BUTTONS_TOP+3*(CONNECTOR_BUTTONS_HEIGHT+CONNECTOR_BUTTONS_DISTANCE)+CONNECTOR_YA,
																BUTTON,
																CONNECTOR_BACK,
																STR_CANCEL,
																OBJECT_ENABLED,
																&connectorSpecialButtonsParams,
																&connectorBackButtonCallback,
																&DrawButton);

	return PASSED;
}

static TIME_STAMP protectStamp;			//Ochranna znamka

/****************************************************************************
	Funkce pro rizeni procesu pripojeni

	Vstup: 
		neni

	Vystup
		OS_STATE:		Stav pripojeni

*****************************************************************************/
OS_STATE HandleConnection(void)
{
	switch(remoteState)
	{
	case OS_STATE_DISC:	
          WifiSendCommand(DRV_WIFI_TEST);							//Odeslani testovaciho prikazu
          connectionHandleStamp = GetTimeStamp();					//cas odeslani prikazu
          remoteState = OS_STATE_INIT;								//Prechod na dalsi stav
          break;
	case OS_STATE_INIT:
          CONNECTOR_WAIT_FOR_RESULT();								//Cekani na odpoved
          strcopy(DRV_WIFI_REMOTE_SERVER_start,commandBuffer);		//Sestaveni prikazu s adresou serveru a portem
          str_append(commandBuffer,remoteIP);
          str_append(commandBuffer,(unsigned char*)":10");
          str_append(commandBuffer,remotePort);
          str_append(commandBuffer,DRV_LINEEND);
          WifiSendCommand(commandBuffer);							//Odeslani prikazu
          remoteState = OS_STATE_ADDRESS;							//Prechod do dalsiho stavu
          break;
	case OS_STATE_ADDRESS:
          CONNECTOR_WAIT_FOR_RESULT();								//Cekani na odpoved
          if (remoteSSL == NO)										//Pokud je pripojeni nesifrovane
          {
            WifiSendCommand(DRV_WIFI_REMOTE_CIPHER_NO);				//Nastaveni sifrovani	
          }
          else
          {
            WifiSendCommand(DRV_WIFI_REMOTE_CIPHER_YES);
          }
          remoteState = OS_STATE_INTERFACE;							//Prechod na dalsi stav
          break;
        case OS_STATE_INTERFACE:
          CONNECTOR_WAIT_FOR_RESULT();								//Cekani na odpoved
          WifiSendCommand(DRV_WIFI_INTERFACE);						//Odelsani prikazu k nastaveni rozhrani
          remoteState = OS_STATE_CIPHER;							//Prechod na dalsi stav
          break;
	case OS_STATE_CIPHER:
          CONNECTOR_WAIT_FOR_RESULT();								//Cekani na odpoved
          WifiSendCommand(DRV_WIFI_REMOTE_SERIAL_NET);				//Prechod do SerialNet modu
          remoteState = OS_STATE_BRIDGE;							//Prechod do dalsiho stavu
          break;
    case OS_STATE_BRIDGE:
        CONNECTOR_WAIT_FOR_RESULT();								//Cekani na odpoved
        remoteState = OS_STATE_CONNECTED;							//Prechod na dalsi stav
        break;
    case OS_STATE_CONNECTED:
    /*if (WifiOnline() != YES)
        break;*/
		remoteState = OS_STATE_ONLINE;								//Prechod do dalsiho stavu
		break;
    case OS_STATE_ONLINE:
		break;
    case OS_STATE_ERROR:
        break;
	}
        return remoteState;
}

/****************************************************************************
	Funkce pro rizeni odpojeni

	Vstup: 
		neni

	Vystup
		OS_STATE:		Stav spojeni

*****************************************************************************/
OS_STATE HandleDisconnect(void)
{
  switch(remoteState)
  {
	case OS_STATE_WAIT:
		if (GetElapsedTime(disconnectStamp)<1000)			//Pokud neuplynula 1s, konec
			break;
		remoteState = OS_STATE_DISCONNECT;					//Prejdi do dalsiho stavu
		WifiSendCommand((unsigned char*)"+++");				//Odeslani prikayu k ukonceni SerialNet
		break;
    case OS_STATE_DISCONNECT:
        if (WifiBusy() == YES)								//Cekani na zpracovani
            break;
        if (WifiOK() == NO)									//Kontrola stavu pripojeni
        {
            remoteState = OS_STATE_ERROR;					//konci chybou
            DebugOut("ERROR\r\n");
            break;
        }
        remoteState = OS_STATE_DISCONNECTED;				//Prechod na stav Dokoncen
        break;
     case OS_STATE_DISCONNECTED:
        break;
     default:
        break;
  }
  return remoteState;
}

/****************************************************************************
	Ridici stavovy automat aplikace

	Vstup: 
		neni

	Vystup
		neni

*****************************************************************************/
void AppConnector(void)
{
	switch (ConnectorInternal.State)
	{
	case CONNECTOR_NOT_INITIALIZED:
		break;
	case CONNECTOR_INITIALIZE:
		ConnectorInternal.State = CONNECTOR_READY;					//Prechod na dalsi stav
		if (ConnectorInitialize() !=PASSED)							//Inicializace
		{
			DebugOut("Connector could not be initialized. Falling to error.\n");
			ConnectorInternal.State = CONNECTOR_ERROR;				//Pokud selhala, selzi
			break;
		}
		DebugOut("Connector initialized.\n");
		break;
	case CONNECTOR_RESTART:
		ConnectorInternal.Startup();								//Akce pro spusteni aplikace
		ConnectorInternal.Screen->EnableAllObjects();				//Povoleni vsech objektu
		ConnectorInternal.State = CONNECTOR_DRAW;					//Prechod na dalsi stav
		//StatusBarTextUpdate(STR_CONNECTION_SETUP);
		break;
	case CONNECTOR_DRAW:
		ConnectorInternal.Screen->Draw();							//vykresleni aplikace
		ConnectorInternal.State = CONNECTOR_ACTIVE;					//Prechod do aktivniho stavu
		break;
	case CONNECTOR_ACTIVE:
		ConnectorInternal.ProceedClick();							//Zpracovani kliknuti
		
		break;
    case CONNECTOR_CONNECTING:
        ConnectorInternal.ProceedClick();							//Zpracovani kliknuti
        if (remoteConnection == OS_WIFI)							//rizeni pripojeni pokud je zvolena wifi
        {
            LedOn(LED_4);
            HandleConnection();
        }
        else
        {
            remoteState = OS_STATE_ONLINE;																		//Jinak nastav stav na Online
        }
                
        if (remoteState != OS_STATE_ONLINE)																		//Pokud neni stav Online
		{
			if (GetElapsedTime(connectionHandleStamp) > 5000)													//Zkontroluj jestli aplikace nezatuhla na moc dlouho
			{
				TDialogCfg cfg = {INFO,COUNTDOWN_NONE,100,(unsigned char*)STR_CONNECTOR_WIFI_FAILED,30};		//Jinak sestav konfiguraci dialogu
				MESSAGE dialogMessage = {CONFIG,&cfg};															//Sestav zpravu pro dialog
				myConnectionState = CONNECTION_ERROR;															//Chyba spojeni
				SendTaskMessage(DIALOG,&dialogMessage);															//Odesli konfiguraci
				ConnectorInternal.RunApplication(DIALOG);														//Spust dialog
			}
			break;
		}
        wifiState = WIFI_IDLE;											//Stav wifi je IDLE
        switch(remoteControl)											//Spust prislusnou aplikaci
        {
        case OS_DESKTOP:
        case OS_TOUCHPAD:          
            ConnectorInternal.RunApplication(DESKTOP);
            break;
        case OS_CONSOLE:
            ConnectorInternal.RunApplication(CONSOLE);
            break;
        }
		LedOff(LED_4);		
        break;
	case CONNECTOR_WAITING:
		switch(ConnectorInternal.TryToResume())							//Cekani na ukonceni dcerine aplikace
		{
		case KEYBOARD:
			switch (startingObject)
			{
			case CONNECTOR_IP_ADDRESS:
				tryToGetIP(remoteIP,KeyboardBuffer.TextBuffer);			//Nacist z klavesnice IP a masku
				tryToGetMask(remotePort,KeyboardBuffer.TextBuffer);
				break;
			}
			break;
		case NONE:
			break;
		case DIALOG:
			
			break;
		default:
            if (remoteConnection == OS_WIFI)							//Pokud bylo spojeni pres wifi, proved ukonceni komunikace
            {
                ConnectorInternal.State = CONNECTOR_DISCONNECT;
                disconnectStamp = GetTimeStamp();
                connectionHandleStamp = GetTimeStamp();
                wifiState = WIFI_WAIT_FOR_RESULT;
                remoteState = OS_STATE_WAIT;
            }
			DebugOut("Returned to Connector from unknown application.\n");
			break;
		}
		break;
	case CONNECTOR_READY:
		break;
    case CONNECTOR_DISCONNECT:
        HandleDisconnect();												//Rizeni odpojeni
        LedOn(LED_4);
        if (remoteState == OS_STATE_DISCONNECTED)						//Pokud bylo spojeni ukonceno
		{
            ConnectorInternal.State = CONNECTOR_STOP;					//Ukonci konektor
            LedOff(LED_4);												
		}
		else if (GetElapsedTime(connectionHandleStamp) > 3000)			//Pokud vyprsel limit spojeni, oznam to uzivateli
		{
				TDialogCfg cfg = {INFO,COUNTDOWN_NONE,100,(unsigned char*)STR_CONNECTOR_WIFI_FAILED,30};	
				MESSAGE dialogMessage = {CONFIG,&cfg};
				SendTaskMessage(DIALOG,&dialogMessage);
				ConnectorInternal.RunApplication(DIALOG);
				LedOff(LED_4);
		}
				
        break;
	case CONNECTOR_STOP:
		ConnectorInternal.Stop();										//Ukoncovaci akce splikace
		break;
	case CONNECTOR_ERROR:
		break;
	default:
		break;
	}
}