/*
             Siemens AG
         Mobile Radio Terminals
          Munich, Germany

.AUTHOR         Kh.Kellerer

.SHORT_DESCR    GAPI Simulation

.SW_COMPONENT   PC-MMI-Testumgebung

.SW_TYPE        Support-File

.STATUS         FIRST VERSION

.CHANGE_CONTROL
Version |  Date  | Changed by      | Reason for Change
0.1      01.02.02  Kh.Kellerer       created
0.2      30.04.02  Kh.Kellerer       show LocalIP, DNS, ...
0.3      19.05.03  N.Barisits (VIE)  added include directive for inc_private_alias.h
0.4      28.11.03  C. Hierl          adaptions due to change to MOPI
0.5      28.05.04  Fang Yunchao (PEK)  Add UNICODE Support

*/

#include "mainfrmh.h"

extern "C"
{
#include <global.h>
#include "gbs.h"
#include "procid.h"
#include "gapievnt.h"
#include "gapidl2h.h"
#include "gapictxh.h"
#include "mopiext.h"
}

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#include "winmain.h"
#include "winrc.h"

#ifdef __WIN32__
extern HANDLE /*hStdIn, */hStdOut; /* standard input, output handles */
#endif

//externals
extern "C" HWND DispGetWinHandle(void);
extern void resizeConBufAndWindow(HANDLE hConsole, SHORT xSize, SHORT ySize);

extern "C" void MOPI_xIPCltConnect(void);

//Prototypes
void WINGAPI_GenerateDlgOutput(HWND hwndDlg);
void wingapi_DisconnectAllConnections(void);

//defines
#define MAX_CONNECTIONS		8
#define NOTIF_CONNECTING	10
//Statics
static unsigned int gConnectionState[MAX_CONNECTIONS];
HWND hGapiDialog = NULL;
char DlgOutputBuffer[255];

////////////////////////////////////////////////////////////////////////////////
void wingapi_InitGlobals(void)
////////////////////////////////////////////////////////////////////////////////
{
	int i;
	for(i=0; i<MAX_CONNECTIONS;i++)
	{
		gConnectionState[i]= IPCLT_NOTIF_DISCONNECTED;
	}
}


#pragma argsused
////////////////////////////////////////////////////////////////////////////////
BOOL CALLBACK WINGAPI_DialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
////////////////////////////////////////////////////////////////////////////////
{
		
	switch (message)
	{
	case WM_GPRS_SIMULATION:
		switch (lParam)
		{
		case NOTIF_CONNECTING:
			gConnectionState[wParam]=(unsigned int)lParam;
			WINGAPI_GenerateDlgOutput(hwndDlg);
			break;				
		case IPCLT_NOTIF_CONNECTED:
		case IPCLT_NOTIF_DISCONNECTING:
		case IPCLT_NOTIF_DISCONNECTED:
			gConnectionState[wParam]=(unsigned int)lParam;
			WINGAPI_GenerateDlgOutput(hwndDlg);
			ForwardMessageToGbs((unsigned int) lParam, (unsigned int) wParam);
			break;				
		case IPCLT_NOTIF_SEND_PERMIT:
		case IPCLT_NOTIF_RECV_AVAIL:
			ForwardMessageToGbs((unsigned int) lParam, (unsigned int) wParam);
			break;

		default:
			print_d("Invalid Message from GPRS simulation!");
			MessageBox( DispGetWinHandle(), _T("Error: Invalid Message from GPRS simulation!"),
				_T("PC-Simulator: GAPI Dialog"),
				(MB_OK | MB_ICONEXCLAMATION) | MB_TASKMODAL );
		}
		//allwas set the focus back to main window
		SetFocus(DispGetWinHandle());
		return TRUE;

	case WM_CLOSE:
		wingapi_DisconnectAllConnections();
		DestroyWindow(hwndDlg);
		hGapiDialog = 0;
		return TRUE;

	default:
		return FALSE;
	}
}

////////////////////////////////////////////////////////////////////////////////
BOOL WINGAPI_OpenDialog( void )
////////////////////////////////////////////////////////////////////////////////
{
	if(hGapiDialog != NULL)
	{
		//Dialog allready open
		return TRUE;
	}
	
	wingapi_InitGlobals();

#ifdef _MSC_VER
	hGapiDialog = CreateDialog(MainApp::hInstance,MAKEINTRESOURCE(IDD_WINGAPI_DIALOG),DispGetWinHandle(),(DLGPROC)WINGAPI_DialogProc);
#else
	hGapiDialog = CreateDialog(MainApp::hInstance,MAKEINTRESOURCE(IDD_WINGAPI_DIALOG),DispGetWinHandle(),(FARPROC)WINGAPI_DialogProc);
#endif
	
	if (hGapiDialog == NULL)
	{
		LPVOID lpMsgBuf;
		FormatMessage( 
			FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | 
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			GetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,
			0,
			NULL 
		);
		// Process any inserts in lpMsgBuf.
		// ...
		// Display the string.
		MessageBox( NULL, (LPCTSTR)lpMsgBuf, _T("Error"), MB_OK | MB_ICONINFORMATION );
		// Free the buffer.
		LocalFree( lpMsgBuf );

		//print_d("ERROR in creating Gapi Dialog!");
		//MessageBox( DispGetWinHandle(), "Error: Could not create Gapi Dialog Window",
		//	"PC-Simulator: Gapi Dialog",
		//	(MB_OK | MB_ICONEXCLAMATION) | MB_TASKMODAL );
		return FALSE;
	}
	
	ShowWindow(hGapiDialog,SW_SHOW);
	return TRUE;
}

extern "C" BOOL cWINGAPI_OpenDialog( void )
{
    return WINGAPI_OpenDialog();
}

////////////////////////////////////////////////////////////////////////////////
void WINGAPI_GenerateDlgOutput(HWND hwndDlg)
////////////////////////////////////////////////////////////////////////////////
{
 	int gcid,currentTextPos=0;
	char IpStr[20];
	unsigned int anMTU= 0;
	memset(IpStr,0x00,sizeof(IpStr));

	memset(DlgOutputBuffer,0x00,sizeof(DlgOutputBuffer));
 
	
	for(gcid=0; gcid<MAX_CONNECTIONS;)
	{
		switch(gConnectionState[gcid])
		{
			case NOTIF_CONNECTING:
				sprintf(DlgOutputBuffer+currentTextPos, " gcid %d:   CONNECTING     \r\n",gcid);
				currentTextPos+=28;
				break;
			case IPCLT_NOTIF_CONNECTED:
				sprintf(DlgOutputBuffer+currentTextPos, " gcid %d:   CONNECTED      \r\n",gcid);
				currentTextPos+=28;
				
				if(IPCLT_NOERROR == xIPCltGetIPAdress(GAPI_Gcid2Ti(gcid), (unsigned char *)IpStr, 20))
				{	
					//(void)enip_ipc_inet_ntoa(anIP, IpStr, sizeof(IpStr));
					sprintf(DlgOutputBuffer+currentTextPos,  "            LocalIP: %s\r\n",IpStr);
				    currentTextPos+=(23+strlen(IpStr));
				}
				if(IPCLT_NOERROR == xIPCltGetDNS1(GAPI_Gcid2Ti(gcid), (unsigned char *)IpStr, 20))
				{	
					//(void)enip_ipc_inet_ntoa(anIP, IpStr, sizeof(IpStr));
					sprintf(DlgOutputBuffer+currentTextPos,  "            DNS1: %s\r\n",IpStr);
				    currentTextPos+=(20+strlen(IpStr));
				}
				if(IPCLT_NOERROR == xIPCltGetDNS1(GAPI_Gcid2Ti(gcid), (unsigned char *)IpStr, 20))
				{	
					//(void)enip_ipc_inet_ntoa(anIP, IpStr, sizeof(IpStr));
					sprintf(DlgOutputBuffer+currentTextPos,  "            DNS2: %s\r\n",IpStr);
				    currentTextPos+=(20+strlen(IpStr));
				}
				if(IPCLT_NOERROR == xIPCltGetMTU(GAPI_Gcid2Ti(gcid), &anMTU))
				{	
					//(void)enip_ipc_inet_ntoa(anIP, IpStr, sizeof(IpStr));
					sprintf(DlgOutputBuffer+currentTextPos,  "            MTU: %5d\r\n",anMTU);
				    currentTextPos+=(19+5);
				}
				break;
			case IPCLT_NOTIF_DISCONNECTING:
				sprintf(DlgOutputBuffer+currentTextPos, " gcid %d:   DISCONNECTING  \r\n",gcid);
				currentTextPos+=28;
				break;
			case IPCLT_NOTIF_DISCONNECTED:
				; //no output
				break;
			default:
				;
		}
		gcid++;
	}
	SendDlgItemMessage(hwndDlg,IDC_WINGAPI_LOGBOX,WM_SETTEXT,0,(LPARAM)&DlgOutputBuffer);
		
	UpdateWindow(hwndDlg);


}

void wingapi_Create_Dlg_Connect(void * pGAPI_MessageParam)
{ 
   ((CMainFrame*) GET_APP()->m_pMainWnd)->PostMessage(WM_CREATE_GAPI_DLG, (WPARAM)pGAPI_MessageParam, (LPARAM) 0);  //send message to main window to create the GAPI Dlg (has to be done inside the WinThreat)
}

extern "C" void cWingapi_Create_Dlg_Connect(void * pGAPI_MessageParam)
{
	wingapi_Create_Dlg_Connect(pGAPI_MessageParam);
}

////////////////////////////////////////////////////////////////////////////////
extern "C" HWND WINGAPI_GetWinHandle(void)
////////////////////////////////////////////////////////////////////////////////
{
	return hGapiDialog;
}

////////////////////////////////////////////////////////////////////////////////
extern "C" void	WINGAPI_ShowConnecting(unsigned int ti)
////////////////////////////////////////////////////////////////////////////////
{
	gConnectionState[ti]= NOTIF_CONNECTING;
	WINGAPI_GenerateDlgOutput(hGapiDialog);
}


////////////////////////////////////////////////////////////////////////////////
void wingapi_DisconnectAllConnections(void)
////////////////////////////////////////////////////////////////////////////////
{
	int ti;

	for(ti=0; ti<MAX_CONNECTIONS;ti++)
	{
		switch(gConnectionState[ti])
		{
			case NOTIF_CONNECTING:
			case IPCLT_NOTIF_CONNECTED:
				//Disconnect DLL
				(void) xIPCltDisconnect(ti);
				//also notify to GAPI
				ForwardMessageToGbs(IPCLT_NOTIF_DISCONNECTED, ti);
				gConnectionState[ti]= IPCLT_NOTIF_DISCONNECTED;
				break;
			default:
				;
		}
	}
}
