#include "stdafx.h"
#include "camwin.h"


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

    MSG msg;
    HACCEL hAccelTable;
	
	////konsola
	//AllocConsole();
	//long  lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
	//int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);	
	//FILE *fp; 
	//fp= _fdopen( hConHandle, "w" );
	//*stdout = *fp;
	//setvbuf( stdout, NULL, _IONBF, 0 );
	

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_CAMWIN, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);
    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

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

    // 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_CAMWIN));
    wcex.hCursor			= LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground		= (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName		= MAKEINTRESOURCE(IDC_CAMWIN);
    wcex.lpszClassName		= szWindowClass;
    wcex.hIconSm			= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_CAMWIN));

    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_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX ,
		CW_USEDEFAULT, 
		0, 
		CW_USEDEFAULT, 
		0, 
		NULL, 
		NULL, 
		hInstance, 
		NULL);


   if (!hWnd)
   {
      return FALSE;
   }
   
   ShowWindow(hWnd, nCmdShow);
   
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  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)
{
	//zmienne inicjalizowane w WM_CREATE
	//poprzednie polozenie x,y okna aplikacji
	static int ox;
	static int oy;
	IplImage *image;
	//aktualna orientacja ekranu
	static int oro;
	static CvCapture *capture;
	static HWND hWndStatus;
	static HWND child;
	static HWND oapp;
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
   
    switch (message)
    {
    case WM_CREATE:	
		{
		child = CreateDialog(hInst,MAKEINTRESOURCE(IDD_FORM),hWnd,(DLGPROC)Form);
		ShowWindow(child, SW_SHOW);
		capture = cvCaptureFromCAM( CV_CAP_ANY );
		image = cvQueryFrame( capture );
		//dopasowywanie okna programu do obrazu z kamery
		SetWindowPos(hWnd,0,0,0,image->width,image->height+70,SWP_NOMOVE|SWP_NOZORDER);
		SetWindowPos(child,0,0,0,image->width,image->height,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
		hWndStatus = CreateWindowEx(0L,STATUSCLASSNAME,L"",WS_CHILD | WS_VISIBLE,0, image->height, image->width,30,hWnd,(HMENU)100,hInst,NULL);
		//podzial status baru na 3 czesci
		int iStatusWidths[] = { 200, 260, - 1 };
		SendMessage( hWndStatus, SB_SETPARTS, 3,( LPARAM ) iStatusWidths );
		cvReleaseImage(&image);
		oro=0;
        ox=-1;
		oy=-1;
		capture=0;
		//potrzebne by dzialaly skroty klawiszowe (akceleratory)
		SetFocus(hWnd);
		}
        break;
        
    case WM_COMMAND:
        wmId    = LOWORD(wParam);
        wmEvent = HIWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
		case IDM_ROTATE:
			{
				if(Disp::DispFuncs::RotateScreen(DMDO_DEFAULT))
				{
					oro=DMDO_DEFAULT;
				}
			}
			break;
        case IDM_ABOUT:
			stopRefresh=true;
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
		case IDM_SELECT:
			stopRefresh=true;
			DialogBox(hInst, MAKEINTRESOURCE(IDD_SELECT), hWnd, Select);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
        
    case WM_MOVE:
        
    case WM_PAINT:
		//hdc = BeginPaint(hWnd, &ps);
		////child = GetDlgItem(hWnd,661);
		////Disp::DispFuncs::CaptureAnImage(child,app,L"captureqwsx.bmp");
		//EndPaint(hWnd, &ps);
		int sts;
        hdc = BeginPaint(hWnd, &ps);
		win_count=0;
		Disp::DispFuncs::CaptureAnImage(child,app,L"captureqwsx.bmp");
		CvPoint2D32f corners[20];
		sts=Disp::DispFuncs::Detect(child,capture,"captureqwsx.bmp",5,4,corners);
		if( sts == DetectionSuccess)
		{
			/*if (ox >= 0 && app != 0)*/
			if (IsWindow(app))
			{
				if (oapp != app)
				{
					wchar_t win_name[40];
					if (GetWindowText(app,win_name,40))
					{
						SendMessage( hWndStatus, SB_SETTEXT, 0,( LPARAM)win_name  );
					}

					HICON icon=NULL;
					if (icon = (HICON)GetClassLong(app, GCL_HICONSM))
					{
						SendMessage( hWndStatus, SB_SETICON, 1,( LPARAM ) icon );
					}
					else
						//sprawdz czy nie ma duzej ikonki
						if(icon = (HICON)GetClassLong(app, GCL_HICONSM))
						{
							SendMessage( hWndStatus, SB_SETICON, 1,( LPARAM ) icon );
						}
				}
				//na wszelki wypadek jesli okno zminimalizowane
				if (ox >= 0)
				{
					ShowWindow(app,SW_RESTORE);
					RECT appPos;
					GetWindowRect(app,&appPos);
					int dx=-ox+corners[0].x;
					int dy=-oy+corners[0].y;	
					SetWindowPos(app,HWND_TOP,appPos.left+dx,appPos.top+dy,0,0,SWP_NOSIZE);
				}
			}
			else
			{
				SendMessage( hWndStatus, SB_SETTEXT, 2,( LPARAM ) L"Skorzystaj z menu File/Wybierz by wybrać okno do przesuwania" );
			}

			ox=corners[0].x;
			oy=corners[0].y;
			//obracanie pulpitu
			int rx,ry;
			rx=corners[4].x-corners[0].x;
			ry=corners[15].x-corners[0].x;
			rx=rx/10;
			ry=ry/10;
			int or;
			//zmiana orientacji ekranu tylko gdy pozycja pionowa lub pozioma kartki
			if(rx>0 && ry==0)
			{
				or=DMDO_DEFAULT;
			}
			else
			{
				if(rx==0 && ry<0)
				{
					or=DMDO_90;
				}
				else
				{
					if(rx<0 &&  ry==0)
					{
						or=DMDO_180;
					}
					else
					{
						if(rx==0 &&  ry>0)
						{
							or=DMDO_270;
						}
						else
						{
							//dla innych przypadkow zachowaj orientacje ekranu
							or=oro;
						}
					}}}

			//printf("rx=%d ry=%d or=%d oro=%d\n",rx,ry,or,oro);
			if (or!=oro)
			{
				if(Disp::DispFuncs::RotateScreen(or))
				{	
					oro=or;
				}
			}
			
			if (oro != DMDO_DEFAULT)
			{
				SendMessage( hWndStatus, SB_SETTEXT, 2,( LPARAM ) L"Wcisnij alt+R by wrócić do normalnego widzenia świata" );
			}
		}
		else
		{
			if (sts==DetectionFail)
			{
				if(IsWindow(app))
				{
					ShowWindow(app,SW_MINIMIZE);
				}
				ox=-1;
				oy=-1;
			}
			else
			{
				DestroyWindow(hWnd);
			}
		}
        EndPaint(hWnd, &ps);
        if (!stopRefresh)
		{	
			RedrawWindow(hWnd,0,0,RDW_INTERNALPAINT);
		}
		break;


    case WM_DESTROY:
		//cvReleaseCapture(&capture);
        PostQuitMessage(0);
        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)
        {
			if (LOWORD(wParam)==IDOK)
			{
				
			}
            EndDialog(hDlg, LOWORD(wParam));
			stopRefresh=false;
			SendMessage(GetParent(hDlg),WM_PAINT,0,0);
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

INT_PTR CALLBACK Select(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{


    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
	case WM_INITDIALOG:
		wchar_t nazwa[40];
		EnumWindows((WNDENUMPROC)EnumWindowsProc,NULL);
		for (int i=0;i<win_count;i++)
		{
			GetWindowText(tabWin[i],nazwa,40);
			SendDlgItemMessage(hDlg,IDC_LIST,LB_ADDSTRING,(WPARAM)-1,(LPARAM)nazwa);
		}
		return (INT_PTR)TRUE;
		break;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
			if (LOWORD(wParam)==IDOK)
			{
				int index=-1;
				index=SendDlgItemMessage(hDlg,IDC_LIST,LB_GETCURSEL,(WPARAM)index,0);
				if (index>=0)
				{
					app=tabWin[index];
					wchar_t nz[40];
					GetWindowText(app,nz,40);
					MessageBox(hDlg,nz,L"nazwa",MB_OK);
				}
			}
            EndDialog(hDlg, LOWORD(wParam));
			stopRefresh=false;
			SendMessage(GetParent(hDlg),WM_PAINT,0,0);
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

bool CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam)
{
		wchar_t nazwa[40];
        if (win_count<200)
        {
			GetWindowText(hwnd,nazwa,40);
			if(IsWindowVisible(hwnd) && wcslen(nazwa)>0 )
			{
				tabWin[win_count]=hwnd;
				win_count++;
			}
          return true;
		}
        else
        {
                return false;
        }
};
LRESULT CALLBACK Form(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	switch(Msg)
	{
	//case WM_COMMAND:
	//	case IDM_ROTATE:
	//		MessageBox(hWndDlg,L"ddds",L"dcdscs",MB_OK);
	//		//Disp::DispFuncs::RotateScreen(DMDO_DEFAULT);
	//		break;
	//	break;
	case WM_INITDIALOG:
		return TRUE;
	}

	return FALSE;
}