// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
#include <mysql.h>
#include <stdio.h>
#include <windows.h>  // For definations as winmain and wndclasses 
#include <tchar.h>  // to handle UNICODE character
#include "resource.h"
#include <SDKDDKVer.h>
#include <string.h>
#include <stdlib.h>
#include<CommCtrl.h>

static TCHAR szWindowClass[] = _T("win32app");

static TCHAR szTitle[] = _T("My first win32 app");

HINSTANCE hInst;

struct st_mysql *conn;

HWND TB_UserName;
HWND TB_Password;
HWND TB_Query;
HWND TB_Result;
HWND TB_Server;
HWND TB_Port;
 
HWND LB_Query;
HWND LB_Result;
HWND LB_UserName;
HWND LB_Password;
HWND LB_Server;
HWND LB_Port;
HWND LB_ConnectionString;

HWND B_Run;
HWND B_CLEAR;
HWND B_Connect;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam);

int CALLBACK WinMain(
	_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPSTR     lpCmdLine,
	_In_ int       nCmdShow)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WndProc;// themain function which will get called whenever u interact with you window
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(32513));
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = NULL;
	wcex.lpszClassName = szWindowClass;
	wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

	wcex.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU);
	wcex.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
	wcex.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON), IMAGE_ICON, 16, 16, 0);

	if (!RegisterClassEx(&wcex))
	{
		MessageBox(NULL,
			_T("Call to RegisterClassEx failed!"),
			_T("Win32 Guided Tour"),
			NULL);

		return 1;
	}

	hInst = hInstance; // Store instance handle in our global variable  

					   // The parameters to CreateWindow explained:  
					   // szWindowClass: the name of the application  
					   // szTitle: the text that appears in the title bar  
					   // WS_OVERLAPPEDWINDOW: the type of window to create  
					   // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)  
					   // 500, 100: initial size (width, length)  
					   // NULL: the parent of this window  
					   // NULL: this application does not have a menu bar  
					   // hInstance: the first parameter from WinMain  
					   // NULL: not used in this application  
	HWND hWnd = CreateWindow(
		szWindowClass,
		szTitle,
		WS_OVERLAPPEDWINDOW,
		7, 7,
		900, 800,
		NULL,
		NULL,
		hInstance,
		NULL
	);

	if (!hWnd)
	{
		MessageBox(NULL,
			_T("Call to CreateWindow failed!"),
			_T("My first window APP"),
			NULL);

		return 1;
	}

	// The parameters to ShowWindow explained:  
	// hWnd: the value returned from CreateWindow  
	// nCmdShow: the fourth parameter from WinMain  
	ShowWindow(hWnd,
		nCmdShow);
	UpdateWindow(hWnd);

	// Main message loop:  
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0; // (int)msg.wParam;
}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{

	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	case WM_CREATE:
	{
		LB_UserName = CreateWindow(
			TEXT("STATIC"),                   /*The name of the static control's class*/
			TEXT("User Name"),                  /*Label's Text*/
			WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
			7,                                /*X co-ordinates*/
			7,                                /*Y co-ordinates*/
			80,                               /*Width*/
			30,                               /*Height*/
			hWnd,                             /*Parent HWND*/
			(HMENU)ID_MYSTATIC,              /*The Label's ID*/
			hInst,                        /*The HINSTANCE of your program*/
			NULL);

	TB_UserName = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, // the styles
		90, 7,                                      // the left and top co-ordinates
		199, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_MYTEXT,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	LB_Password = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT("Password"),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		302,                                /*X co-ordinates*/
		7,                                /*Y co-ordinates*/
		80,                               /*Width*/
		30,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_MYSTATIC,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);

	TB_Password = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, // the styles
		387, 7,                                      // the left and top co-ordinates
		199, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_PASSWORD,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	LB_Server = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT("Server"),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		7,                                /*X co-ordinates*/
		42,                                /*Y co-ordinates*/
		80,                               /*Width*/
		30,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_MYSTATIC,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);

	TB_Server = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, // the styles
		90, 42,                                      // the left and top co-ordinates
		199, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_Server,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	LB_ConnectionString = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT(""),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		7,                                /*X co-ordinates*/
		95,                                /*Y co-ordinates*/
		600,                               /*Width*/
		35,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_CONNECTIONSTRING,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);

	LB_Port = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT("Port"),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		302,                                /*X co-ordinates*/
		42,                                /*Y co-ordinates*/
		80,                               /*Width*/
		30,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_MYSTATIC,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);


	TB_Port = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, // the styles
		387, 42,                                      // the left and top co-ordinates
		199, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_PORT,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	B_Connect = CreateWindow(
		TEXT("Button"),                              // The class name required is edit
		TEXT("Connect"),                                 // Default text.
		WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // the styles
		620, 25,                                      // the left and top co-ordinates
		80, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_CONNECT,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	///////////////////////////////////End of connect section ////////////////////////////////////////////////////////

	LB_Query = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT("Query Window"),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		7,                                /*X co-ordinates*/
		150,                                /*Y co-ordinates*/
		100,                               /*Width*/
		30,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_MYSTATIC,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);

	B_Run = CreateWindow(
		TEXT("Button"),                              // The class name required is edit
		TEXT("Run The Query"),                                 // Default text.
		WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // the styles
		620, 180,                                      // the left and top co-ordinates
		100, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_RUN,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	B_CLEAR = CreateWindow(
		TEXT("Button"),                              // The class name required is edit
		TEXT("Clear"),                                 // Default text.
		WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // the styles
		620, 220,                                      // the left and top co-ordinates
		100, 30,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_CLEAR,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	EnableWindow(GetDlgItem(hWnd, ID_RUN), FALSE);
	EnableWindow(GetDlgItem(hWnd, ID_CLEAR), FALSE);

	TB_Query = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_MULTILINE, // the styles
		7, 180,                                      // the left and top co-ordinates
		600, 250,                                  // width and height
		hWnd,                                     // parent window handle
		(HMENU)ID_QUERY,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	LB_Result = CreateWindow(
		TEXT("STATIC"),                   /*The name of the static control's class*/
		TEXT("Result Window"),                  /*Label's Text*/
		WS_CHILD | WS_VISIBLE | SS_LEFT,  /*Styles (continued)*/
		7,                                /*X co-ordinates*/
		440,                                /*Y co-ordinates*/
		100,                               /*Width*/
		30,                               /*Height*/
		hWnd,                             /*Parent HWND*/
		(HMENU)ID_MYSTATIC,              /*The Label's ID*/
		hInst,                        /*The HINSTANCE of your program*/
		NULL);

	TB_Result = CreateWindow(
		TEXT("EDIT"),                              // The class name required is edit
		TEXT(""),                                 // Default text.
		WS_VISIBLE | WS_CHILD | WS_BORDER | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_MULTILINE | EM_SETREADONLY, // the styles
		7, 470,                                      // the left and top co-ordinates
		600, 250,                                  // width and heightc
		hWnd,                                     // parent window handle
		(HMENU)ID_RESULT,                         // the ID of your editbox
		hInst,                                // the instance of your application
		NULL);

	///////////////////////////////////// End of layout ////////////////////////////////

	}

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case ID_FILE_EXIT:
			PostQuitMessage(0);

		case ID_CONNECT: 
		{
			////////////////////////////////////get the username and password//////////////////////////
			RECT rcClient;  // dimensions of client area 
			HWND hwndTV;    // handle to tree-view control 

							// Ensure that the common control DLL is loaded. 
			//InitCommonControls();
			TVITEM tvi, tvItem;
			TVINSERTSTRUCT tvins;
			static HTREEITEM hPrev = (HTREEITEM)TVI_FIRST;
			static HTREEITEM hPrevRootItem = NULL;
			static HTREEITEM hPrevLev2Item = NULL;
			HTREEITEM hti ;
			// Get the dimensions of the parent window's client area, and create 
			// the tree-view control. 
			GetClientRect(hWnd, &rcClient);
			hwndTV = CreateWindowEx(0,
				WC_TREEVIEW,
				TEXT("Tree View"),
				WS_VISIBLE | WS_CHILD | WS_BORDER | TVS_HASLINES,
				0,
				0,
				rcClient.right,
				rcClient.bottom,
				hWnd,
				(HMENU)IDTREE,                         // the ID of your editbox
				hInst, 
				NULL);

			hti = hwndTV;
			tvi.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE;
			tvi.hItem = hti;
			tvi.state = 1;
			tvi.pszText = "Node";
			//tvi.iImage = g_nClosed;
			//tvi.iSelectedImage = g_nClosed;
			/*(HTREEITEM)SendMessage(hwndTV, TVM_INSERTITEM,
				0, (LPARAM)(LPTVINSERTSTRUCT)&tvi);*/
			TVINSERTSTRUCT tvis;
			memset(&tvis, 0, sizeof(tvis));
			tvis.hParent = hwndTV /*TVI_ROOT*/;    // Have tried both sets of values
			tvis.hInsertAfter =TVI_FIRST;
			tvis.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
			tvis.item.pszText = (LPTSTR)(LPCTSTR)"tt";
			//tvis.item.iImage = nImage;
			//tvis.item.iSelectedImage = nImage;
			tvis.item.state = 0;
			tvis.item.stateMask = 0;
			//tvis.item.lParam = reinterpret_cast<LPARAM>(tvi.get());


			HTREEITEM hItem;
			TreeView_InsertItem(hwndTV, &tvis);
		
			memset(&tvis, 0, sizeof(tvis));
			tvis.hParent = hwndTV /*TVI_ROOT*/;    // Have tried both sets of values
			tvis.hInsertAfter = hwndTV;
			tvis.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
			tvis.item.pszText = (LPTSTR)(LPCTSTR)"pp";
			//tvis.item.iImage = nImage;
			//tvis.item.iSelectedImage = nImage;
			tvis.item.state = 0;
			tvis.item.stateMask = 0;

			 TreeView_InsertItem(hwndTV, &tvis);

			 hti = TreeView_GetChild(hwndTV, tvi.hItem);

			 int i = tvi.state;

			 TreeView_SetCheckState(hwndTV, tvi.hItem, 0);

			////////

			//TreeView_SetCheckState(hWnd, hti, 1);

			LRESULT szUserName = SendMessage(TB_UserName, EM_GETLIMITTEXT, 0, 0);
			char *sUserName = (char *) malloc(szUserName *sizeof(szUserName));
			SendMessage(TB_UserName, WM_GETTEXT, szUserName, (LPARAM)sUserName);

			LRESULT szPassword = SendMessage(TB_Password, EM_GETLIMITTEXT, 0, 0);
			char *sPassword = (char *)malloc(szPassword * sizeof(szPassword));
			SendMessage(TB_Password, WM_GETTEXT, szPassword, (LPARAM)sPassword);

			LRESULT szServer = SendMessage(TB_Server, EM_GETLIMITTEXT, 0, 0);
			char *sServer = (char *)malloc(szServer * sizeof(szServer));
			SendMessage(TB_Server, WM_GETTEXT, szServer, (LPARAM)sServer);

			LRESULT szPort = SendMessage(TB_Port, EM_GETLIMITTEXT, 0, 0);
			char *sPort = (char *)malloc(szPort * sizeof(szPort));
			SendMessage(TB_Port, WM_GETTEXT, szPort, (LPARAM)sPort);

			int Port = (atoi)(sPort);

			char *String = (char *)calloc(sizeof(int),1000);
			char *database = "sakila";

			strcat(String, "Connection Details: Server  ");

			strcat(String, sServer);
			strcat(String, ", ");
			strcat(String, "UserName ");
			strcat(String, sUserName);
			strcat(String, ", ");
			strcat(String, "Database ");
			strcat(String, database);

			////////////////////////////////////Establish the connection//////////////////////////
		
			
			conn = mysql_init(NULL);
			if (!conn)
			{
				MessageBox(NULL,
					_T("Initialisation Instance Failed!!!"),
					_T("Connect to MYSQL Local host"),
					NULL);
				exit(1);
			}
			mysql_options(conn, MYSQL_OPT_RECONNECT, (const char *)"true");
			mysql_options(conn, MYSQL_INIT_COMMAND, "SET NAMES 'utf8' COLLATE 'utf8_polish_ci'");
			conn = mysql_real_connect(conn, sServer, sUserName, sPassword, NULL, Port, NULL, 1);

			if (!conn)
			{
					MessageBox(NULL,
					_T("Not Connected !!!"),
					_T("Connect to MYSQL Local host"),
					NULL);
			}
			else
			{
				SendMessage(TB_UserName, WM_SETTEXT, 0, (LPARAM)"");
				SendMessage(TB_Password, WM_SETTEXT, 0, (LPARAM)"");
				SendMessage(TB_Server, WM_SETTEXT, 0, (LPARAM)"");
				SendMessage(TB_Port, WM_SETTEXT, 0, (LPARAM)"");

				SendMessage(LB_ConnectionString, WM_SETTEXT, 0, (LPARAM)String);

				EnableWindow(GetDlgItem(hWnd, ID_CONNECT),FALSE);
				EnableWindow(GetDlgItem(hWnd, ID_CONNECTIONSTRING), TRUE);
				

				MessageBox(NULL,
					_T("Connected !!!"),
					_T("Connect to MYSQL Local host"),
					NULL);
				EnableWindow(GetDlgItem(hWnd, ID_RUN), TRUE);
				EnableWindow(GetDlgItem(hWnd, ID_CLEAR), TRUE);
			}
			break;
		}
		case ID_RUN:
		{

			LRESULT szQuery = SendMessage(TB_Query, EM_GETLIMITTEXT, 0, 0);
			char *sQuery = (char *)malloc(szQuery * sizeof(szQuery));
			SendMessage(TB_Query, WM_GETTEXT, szQuery, (LPARAM)sQuery);

			MYSQL_RES *Res;  
			MYSQL_FIELD *field;
			int r = mysql_query(conn, sQuery);
			
			if (r) {
				MessageBox(NULL, mysql_error(conn), _T("Connection error"), NULL);
			}
			unsigned int number_of_columns = 0;	
		    int num_rows = 0;
			char* buffer = (char *)calloc(255, sizeof(char));
			Res = mysql_store_result(conn);
			
			
			if (Res)
			{
				number_of_columns = mysql_num_fields(Res);
				//sprintf(buffer, "%d", number_of_columns);
				//SendMessage(TB_Result, WM_SETTEXT, 0, (LPARAM)buffer);
				MYSQL_ROW row;
				char* str = (char *)calloc((10000* number_of_columns), sizeof(char));
				int i = 0;

				if (i == 0) {
					while (field = mysql_fetch_field(Res))
					{
						strcat(str, field->name);
						strcat(str, "\t");
					}
					strcat(str, "\r\n");
					strcat(str, "\r\n");
				}

				while ((row = mysql_fetch_row(Res)) != NULL)
				{
					for (i = 0; i < number_of_columns; i++)
					{
						strcat(str, row[i]);
						strcat(str, "\t");
					}
					strcat(str, "\r\n");
				}
				SendMessage(TB_Result, WM_SETTEXT, 0, (LPARAM)str);
				mysql_free_result(Res);
			}
			else
			{
				int i = mysql_field_count(conn);
				if (i == 0)
				{
					num_rows = mysql_affected_rows(conn);
					sprintf(buffer, "%d", num_rows);
					strcat( buffer," rows affected");
					SendMessage(TB_Result, WM_SETTEXT, 0, (LPARAM)buffer);
				}
			}
					
		}							  
			break;

		case ID_CLEAR:
		{
			SendMessage(TB_Query, WM_SETTEXT, 0, (LPARAM)"");
		}

		}

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
		break;
	}

	return 0;
}


BOOL CALLBACK AboutDlgProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
	
	switch (Message)
	{
	case WM_CREATE:
	{
		
	}
	case WM_INITDIALOG:

		return TRUE;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case IDOK:
			EndDialog(hWnd, IDOK);
			break;
		case IDCANCEL:
			EndDialog(hWnd, IDCANCEL);
			break;
		}
		break;
	default:
		return FALSE;
	}
	return TRUE;
}


