//
//wingui.c
//
//Contains windows gui and interface functions. Also contains WinMain().
//
//-UserX 2001/11/05

#include "misc/compat.h"
#ifdef _WINDOZE_

#include <windows.h>
#include <winsock.h>

#include <shellapi.h>
#include <stdio.h>

#include "iip/iip.h"

#include "base/str.h"

#include "base/cfg.h"
#include "iip/wingui.h"

#include "net/nodeserv.h"

#include "iip/winrc/resource.h"


#include "iip/iip-ui.h"
#include "ui/ui-win.h"

#define NOTIFY (WM_USER + 1)

  /* Winsock needs additional startup activities */
WSADATA wsadata;
HWND hwnd;

HINSTANCE hinst = NULL;

int settingsshown = 0;

static UINT s_uTaskbarRestart;

void winguiShowVersion(void) {
	char *msg;
	msg = stringJoinMany(
		VERSIONTEXT,
		NULL);
	MessageBox(hwnd, msg, _("Version"), MB_OK);
	stringFree(msg);
}

BOOL AddTrayIcon(LPSTR ToolTip,UINT uID, HINSTANCE hinstance)
{
	BOOL result;
	NOTIFYICONDATA IconDat;
	HICON hIcon1;   /* icon handle            */ 
	
	hIcon1 = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON_IIP)); 


	IconDat.cbSize	= sizeof(NOTIFYICONDATA);
	IconDat.hWnd	= hwnd;
	IconDat.uID		=uID;
	//strcpy(IconDat.szTip,ToolTip);
	memcpy(IconDat.szTip, ToolTip, sizeof(IconDat.szTip) - 1);
	IconDat.szTip[sizeof(IconDat.szTip) - 1] = 0;
	IconDat.uCallbackMessage = NOTIFY;
	IconDat.hIcon = hIcon1;
	IconDat.uFlags = NIF_MESSAGE |  
					 NIF_ICON |     
					 NIF_TIP;  
	result = Shell_NotifyIcon(NIM_ADD, &IconDat); 

//	if (hIcon1) 
  //      DestroyIcon(hIcon1); 

	
	return result;
}
  
BOOL DeleteTrayIcon(UINT uID) 
{
	BOOL result;
	NOTIFYICONDATA IconDat;
	IconDat.cbSize	= sizeof(NOTIFYICONDATA);
	IconDat.hWnd	= hwnd;
	IconDat.uID		=uID;
	
	result = Shell_NotifyIcon(NIM_DELETE, &IconDat); 
	return result;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	POINT mouse;
//	int choice;
	HMENU hmenu;
	int i;
	char *s;
	switch (msg) {
	case NOTIFY:
		//DeleteTrayIcon(5005)
		switch(lparam) {
		case WM_LBUTTONDBLCLK:
			SetForegroundWindow(hwnd); // Our MessageBox pops up in front
			//DialogBox(hinst, MAKEINTRESOURCE(IDD_DIALOG_CLIENT_SETTINGS), hwnd, DProcCS);
			iipcsScreen();

			/*
			SetForegroundWindow(hwnd); // Our MessageBox pops up in front
			choice = MessageBox(hwnd, "Do you really want to stop isproxy", "Isproxy", MB_YESNO | MB_DEFBUTTON2);
			if(choice==IDYES) {
				DeleteTrayIcon(5005);
				PostQuitMessage(0);
			}
			*/
			break;
		case WM_RBUTTONUP: //WM_CONTEXTMENU:
			if(GetCursorPos(&mouse)) {
				hmenu = CreatePopupMenu();
				AppendMenu(hmenu, MF_STRING, IDM_VERSION, "Version");
				AppendMenu(hmenu, MF_STRING, IDM_HELP, "Help");
				if(settingsshown == 0) {
					AppendMenu(hmenu, MF_STRING, IDM_SETTINGS, "Settings");
				}
				AppendMenu(hmenu, MF_STRING, IDM_EXIT, "Exit");
				i = TrackPopupMenu(hmenu, TPM_RIGHTBUTTON | TPM_RETURNCMD , mouse.x, mouse.y, 0, hwnd, NULL); //TPM_LEFTALIGN | TPM_BOTTOMALIGN
				DestroyMenu(hmenu);
				switch(i) {
				case IDM_VERSION:
					winguiShowVersion();
					break;
				case IDM_HELP:
					//HtmlHelp(hwnd, winhelpfile, HH_DISPLAY_TOPIC, 0);
					//todo: figure out what is needed for html help
					s = stringAppend("hh ", winhelpfile);
					i = WinExec(s, SW_SHOW);
					stringFree(s);
					if(i != 0 && i <= 31) {
						s = stringAppend("start ", winhelpfile2);
						i = WinExec(s, SW_SHOW);
						stringFree(s);
					}
					break;
				case IDM_EXIT:
					DeleteTrayIcon(5005);
					PostQuitMessage(0);
					return(0);
				case IDM_SETTINGS:
					//IDD_DIALOG_CLIENT_SETTINGS
					//DialogBox(hinst, MAKEINTRESOURCE(IDD_DIALOG_CLIENT_SETTINGS), hwnd, DProcCS);
					if(settingsshown == 0) {
						settingsshown = 1;
						iipcsScreen();
						settingsshown = 0;
					}
					break;
				}
			}
			break;
		}
		break;
	case WM_DESTROY:
		DeleteTrayIcon(5005);			
		PostQuitMessage(0);
		return(0);
    default:
        if(msg == s_uTaskbarRestart) {
			AddTrayIcon("Invisible IRC running", 5005, hinst);
		}
        break;
	}
	return DefWindowProc(hwnd, msg, wparam, lparam);
}




//int WINAPI WinMain2(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline,int ncmdshow)
//int winguiMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline,int ncmdshow) 
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline,int ncmdshow) {

  
	WNDCLASSEX			winclass;			//Unsere Klasse
	int i;
//  SOCKET lsock;
//  HANDLE stdinput,stdoutput;
//  DWORD written,read;
//  char buf[4096];
//  struct sockaddr_in laddr, oaddr;
//  struct client_t clients[MAXNODES];
	char *msg;

	hinst = hinstance;

	initfirst();

	configSetWinCL(lpcmdline);
	uiSetFuncs(uiwinMake, uiwDialog, uiwGetEntropy);

	initsecond();

	/* Winsock needs additional startup activities */
	WSAStartup(MAKEWORD(1,1), &wsadata);
  
	winclass.cbSize			= sizeof(WNDCLASSEX);
	winclass.style			= CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	winclass.lpfnWndProc	= WindowProc;
	winclass.cbClsExtra		= 0;
	winclass.cbWndExtra		= 0;
	winclass.hInstance		= hinstance;
	winclass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	winclass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	winclass.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
	winclass.lpszMenuName	= NULL;
	winclass.lpszClassName	= "isproxy";
	winclass.hIconSm		= LoadIcon(NULL, IDI_APPLICATION);

	//Registrierung der Window Klasse


	if (!RegisterClassEx(&winclass))
		return(666);
	hwnd = CreateWindowEx(0, "isproxy", "isproxy", WS_POPUP, CW_USEDEFAULT, 0,
		CW_USEDEFAULT, 0, NULL, NULL, hinstance, NULL);

	s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));

	if(showversion != 0) {
		winguiShowVersion();
		showversion = 0;
	}
	if(makeKeys == 0) {
		if (localPort == -1) {
			nodeservClearListenRefs();
			nodeservReadListenRefFile();
			//DialogBox(hinstance, MAKEINTRESOURCE(IDD_DIALOG_GETPORTNUM), hwnd, DProc); //MAKEINTRESOURCE(101),
			//DialogBox(hinstance, MAKEINTRESOURCE(IDD_DIALOG_CLIENT_SETTINGS), hwnd, DProcCS);
			iipcsScreen();
			doconfig = 0;
			if (localPort == -1) {
				return(10);
			}
			SetFocus(hwnd);
			msg = stringJoinMany(
				"In your IRC client, log on to IIRC by typing \"/server 127.0.0.1 ",
				intToString(localPort),
				"\" and then type \"/join #anonymous\".",
				NULL);
			MessageBox(hwnd, msg, "Connect to IIP", MB_OK);
			stringFree(msg);
		} else {
		}

	}
	//i = (int) MAKEINTRESOURCE(IDR_MENU_TRAY);
	//i = GetLastError();


	AddTrayIcon("Invisible IRC running", 5005, hinstance);

/*
	if(!AllocConsole()!=0)return(999);
	//CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,0,
	//						  NULL,CONSOLE_TEXTMODE_BUFFER,NULL);
	//SetConsoleActiveScreenBuffer(stdoutput);
	stdinput = GetStdHandle(STD_INPUT_HANDLE);
	stdoutput = GetStdHandle(STD_OUTPUT_HANDLE);
	
	if(stdinput == INVALID_HANDLE_VALUE || stdoutput == INVALID_HANDLE_VALUE)return(555);

	WriteConsole(stdoutput,"\nSelect Port you would like to use to connect to:",strlen("\nSelect Port you would like to use to connect to:"),&written,NULL);
	ReadConsole( 
            stdinput,    // input handle
            buf, //localport,  // buffer to read into 
            sizeof(buf), //4,       // size of buffer
            &read,    // actual bytes read
            NULL);     // not overlapped
      
	localPort = atoi(buf);

*/
	i = init();
	DeleteTrayIcon(5005);
	return i;
}	


int dowindows() {
	MSG					winmsg;
	if (PeekMessage(&winmsg,NULL,0,0,PM_REMOVE))		//teste msg auf Nachricht, wenn ja holen
	{
		if (winmsg.message == WM_QUIT) {
			return 1;
		}
			
		TranslateMessage(&winmsg);

		DispatchMessage(&winmsg);
	}
	return 0;
}

#endif  //Ending SkyRat's code


