// malarz.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "commdlg.h"
#include "malarz.h"
#include <fstream>


#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;								// current instance
static OPENFILENAME ofn;
static OPENFILENAME sfn;
DWORD aktkolor=0x00ffffff;
static CHOOSECOLOR kolor;
LPCTSTR filtr[4];
LPCTSTR dom_roz="bmp";
static char nazwa_pliku_odczyt[3*1024];
static char nazwa_pliku_zapis[3*1024];
HANDLE bitmapa;
BITMAP bit_wymiar;
RECT up;
int sxm,sym;
int xm,ym;
bool otworz=0;

TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_MALARZ, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MALARZ));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MALARZ));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_MALARZ);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}
void Zapisz24BitBMP(char* name,HANDLE MapaBitowa,int bitmap_dx, int bitmap_dy)
{
HDC hdcc;
LPBITMAPINFO info;
LPBYTE lpBits;
std::ofstream file;

BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;

fileHeader.bfType=0x4d42;
fileHeader.bfSize=0;
fileHeader.bfReserved1=0;
fileHeader.bfReserved2=0;
fileHeader.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

infoHeader.biSize = sizeof(infoHeader);
infoHeader.biWidth = bitmap_dx;
infoHeader.biHeight = bitmap_dy;
infoHeader.biPlanes = 1;
infoHeader.biBitCount = 24;
infoHeader.biCompression = BI_RGB;
infoHeader.biSizeImage = 0;
infoHeader.biXPelsPerMeter = 0;
infoHeader.biYPelsPerMeter = 0;
infoHeader.biClrUsed = 0;
infoHeader.biClrImportant = 0;

file.open(name,std::ios::binary);
file.write((char*)&fileHeader,sizeof(fileHeader));
file.write((char*)&infoHeader,sizeof(infoHeader));

hdcc = CreateCompatibleDC(NULL);
SelectObject(hdcc,MapaBitowa);
lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED,bitmap_dx*bitmap_dy*sizeof(RGBQUAD));
info = (LPBITMAPINFO)GlobalAlloc(GMEM_FIXED,sizeof(BITMAPINFO));
info->bmiHeader = infoHeader;
GetDIBits(hdcc, (HBITMAP)MapaBitowa,0,(WORD) bitmap_dy,lpBits,info,DIB_RGB_COLORS);
file.write((LPSTR) lpBits, (int) bitmap_dx*bitmap_dy*sizeof(RGBQUAD));
file.close();
DeleteDC(hdcc);

}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	HDC hdcc;
	HPEN hPen = NULL;
	HGDIOBJ prevhPen = NULL;



	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case IDM_OPEN:
			filtr[0]="Bitmapy";
			filtr[1]="*.BMP";
			filtr[2]="Wszytskie pliki";
			filtr[3]="*.*\0";
			nazwa_pliku_odczyt[0]='\0';
			ZeroMemory(&ofn,sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.hwndOwner = hWnd;
			ofn.lpstrFile = nazwa_pliku_odczyt;
			ofn.nMaxFile = sizeof(nazwa_pliku_odczyt);
			ofn.lpstrTitle = "Otwórz plik";
			ofn.lpstrFilter = filtr[0];
			ofn.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
			otworz=1;
			if (GetOpenFileName(&ofn)) {
				bitmapa = LoadImage(hInst,nazwa_pliku_odczyt,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
				GetObject(bitmapa,sizeof(bit_wymiar),&bit_wymiar);
			}
			InvalidateRect(hWnd,NULL,TRUE);
			 break;

		case IDM_COLOR:
			static DWORD standard[16];
			ZeroMemory(&kolor,sizeof(CHOOSECOLOR));
			kolor.lStructSize=sizeof(CHOOSECOLOR);
			kolor.hwndOwner=hWnd;
			kolor.rgbResult=aktkolor;
			kolor.lpCustColors=(LPDWORD) standard;
			kolor.Flags=CC_FULLOPEN|CC_RGBINIT;
			if (ChooseColor(&kolor))
			aktkolor=kolor.rgbResult;
			break;
		case IDM_SAVE:
			ZeroMemory(&sfn,sizeof(sfn));
			sfn.lStructSize = sizeof(sfn);
			sfn.hwndOwner = hWnd;
			sfn.lpstrFile = nazwa_pliku_zapis;
			sfn.nMaxFile = sizeof(nazwa_pliku_zapis);
		    sfn.lpstrTitle = "Zapisz plik";
			filtr[0]="Bitmapy";
			filtr[1]="*.BMP";
			filtr[2]="Wszytskie pliki";
	     	filtr[3]="*.*\0";
		 	sfn.lpstrFilter = filtr[0];
			sfn.lpstrDefExt = dom_roz;
			sfn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
			if (GetSaveFileName(&sfn)) {
				Zapisz24BitBMP(sfn.lpstrFile,bitmapa,bit_wymiar.bmWidth,bit_wymiar.bmHeight);
				ZeroMemory(&sfn,sizeof(sfn));
			} 
			break; 
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		hdcc=CreateCompatibleDC(hdc);
		SelectObject(hdcc,bitmapa);
		hPen=CreatePen(PS_SOLID,1,aktkolor);
		prevhPen=SelectObject(hdcc,hPen);


		if (otworz!=1) {
			MoveToEx(hdcc,sxm,sym,NULL);
			LineTo(hdcc,xm,ym);
			sxm=xm;
			sym=ym;
		}
		SelectObject(hdcc,prevhPen);
		DeleteObject(hPen);
		otworz=0;
		BitBlt(hdc,0,0,bit_wymiar.bmWidth,bit_wymiar.bmHeight,hdcc,0,0,SRCCOPY);
		DeleteDC(hdcc);
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_LBUTTONDOWN:
		sxm=LOWORD(lParam);
		sym=HIWORD(lParam);
	break;
	case WM_MOUSEMOVE:
		if (wParam==MK_LBUTTON) {
			xm=LOWORD(lParam);
			ym=HIWORD(lParam);
			up.left=xm-10;
			up.top=ym-10;
			up.right=xm+10;
			up.bottom=ym+10;
			InvalidateRect(hWnd,&up,TRUE);
			UpdateWindow(hWnd);
		}
   break;

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
