// psx.cpp : Defines the entry point for the application.
//
#include "xbox_stdafx.h"

#include <xtl.h>
#include <xui.h>    // XUI Runtime
#include <xuiapp.h> // XUI Class Library
#include "Cemulator.h"
#include "Running.h"
#include "HttpClient.h"
#include "cprintf.h"

#ifdef USE_NET_SECURITY

HRESULT InitNet()
{
	DWORD dwResult;
    XNetStartupParams xnsp;
    XNADDR xna;

    XMemSet( &xnsp, 0, sizeof( xnsp ) );
    xnsp.cfgSizeOfStruct = sizeof( XNetStartupParams );
    xnsp.cfgFlags = XNET_STARTUP_BYPASS_SECURITY;   // Allow unsecured communications. Only relevant on the Xbox 360 development kit, 
    // This flag is silently ignored when when running on retail hardware.
    dwResult = XNetStartup( &xnsp );
    if( dwResult != 0 )
        return E_FAIL;                              // error XNET startup

    do
    {
        dwResult = XNetGetTitleXnAddr( &xna );
    } while( dwResult == XNET_GET_XNADDR_PENDING );

    WORD wVersionRequested = MAKEWORD( 2, 2 );
    WSADATA wsaData;

    dwResult = WSAStartup( wVersionRequested, &wsaData );
    if( dwResult != 0 )
        return E_FAIL;                            // initialization failed

    // Confirm that version 2.2 is supported.
    // Note that ifthe implementation supported versions
    // greater than 2.2, it would still return 2.2 in
    // wVersion since that is the version we requested.
    if( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 )
    {
        // We only want 2.2 and this implementation doesn't
        // support it.  This will not happen in Xbox 360 Winsock.
        return E_FAIL;
    }
	return S_OK;
};

HRESULT HTTPGetResult(const char *server, char *query)
{
	HttpClient httpclient;

	HRESULT ret = httpclient.GET(server,query);
	if( ret == E_PENDING )
	while( httpclient.GetStatus() == HttpClient::HTTP_STATUS_BUSY )
    {
		Sleep(5);
    }


	if(httpclient.GetStatus()!=HttpClient::HTTP_STATUS_DONE)
	{
		if( httpclient.GetSocketErrorCode() )
			printf( "Load %s failed!\r\nERROR %d", server, httpclient.GetSocketErrorCode() );
        else
			printf( "Load %s failed!\r\nHTTP %d", server, httpclient.GetResponseCode() );
		return E_FAIL;
	}
	else 
	{
		printf("Load %s Ok!\r\nERROR %d", server, httpclient.GetSocketErrorCode() );
		return S_OK;
	}
}
//-------------------------------------------------------------------------------------
// Se connect en ligne pour savoir si on peut jouer 
//-------------------------------------------------------------------------------------
HRESULT NetSecurity()
{
	//Recupe l'identifiant
	VOID* pSectionData;
    DWORD dwSectionSize;

	if( !XGetModuleSection( GetModuleHandle( NULL ), "ID", &pSectionData, &dwSectionSize ) )
        return E_FAIL;

	char * identififant = (char*) pSectionData;
	
	char query[0x3000];
	sprintf(query, AUTH_PAGE, "10");

	if(FAILED(HTTPGetResult(AUTH_SERV ,query)))
	{
		OutputDebugString("Failed !!");
		//reboot !!
		XLaunchNewImage( "", 0 );
		return E_FAIL;
	}

	return S_OK;
}

DWORD WINAPI NetSecurityThread(LPVOID lpParameter)
{
	while(1)
	{
		Sleep(5000);//30sec
		if( FAILED(NetSecurity() ) )
		{
			//break;
		}
		
	}
	DebugBreak();
	return E_FAIL;
}
#endif
//-------------------------------------------------------------------------------------
// Name: main()
// Desc: The application's entry point
//-------------------------------------------------------------------------------------
void __cdecl main()
{
#ifdef USE_NET_SECURITY
	InitNet();

	DWORD m_dThreadId;
	HANDLE hThread = CreateThread( 
		NULL,                   // default security attributes
		0,                      // use default stack size  
		NetSecurityThread,			// thread function name
		NULL,					// argument to thread function 
		CREATE_NEW,       // use default creation flags 
		&m_dThreadId			// returns the thread identifier 
	); 
#endif

	Cemulator & c = Cemulator::GetInstance();
	c.InitE();
	//c.InitVideo();
	c.InitVideo();
	InitConfig();
#ifndef CC_BUILD
	c.InitXui();
#endif

#ifdef CC_BUILD
#ifdef USE_DISPLAY_THREAD 
	c.SetupThread();
#endif
#endif
	//setup the display thread...
#ifdef CC_BUILD
	RunPsx(); //<- this always running => no exit(restart) work
#else
	while(c.IsXuiDisplayed()){
		c.RenderVideo();
		//c.RenderXui();
	};
#ifdef USE_DISPLAY_THREAD 
	c.SetupThread();
#endif

	//c.StartEmulation();
	RunPsx();

#endif
	DebugBreak();//ne doit jamais arrivé la !!!
	
}

