#include "application.h"

Application Mosaic;

// The main message loop for the application.
LRESULT WINAPI wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_DESTROY:
			// Release all objects and quit.
            Mosaic.Release();
            PostQuitMessage(0);
            return 0;
		case WM_KEYDOWN:
			//Send key to application.
			Mosaic.SetKey(wParam);
			break;
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

// Main application entry point.
INT WINAPI WinMain(HINSTANCE hThisApInst, HINSTANCE hPrevApInst, LPSTR lpCmdLine, INT nWindowShowState)
{
	// Initialise application with arguments.
	Mosaic.Init(lpCmdLine);

	// Create window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, wndProc, 0L, 0L, 
                      GetModuleHandle(NULL), LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON)), NULL, NULL, NULL,
                      "Mosaic", NULL };

	// Register window class.
    RegisterClassEx(&wc);

	// Create window.
	HWND hWnd = CreateWindow("Mosaic", "Mosaic Audio Visualiser", 
							WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, Mosaic.Properties.Width, Mosaic.Properties.Height,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL);

	// If the start method succeeds, begin the main application loop.
	if(Mosaic.Start(hWnd, wc.hInstance))
    { 
		ShowWindow(hWnd, SW_SHOWDEFAULT);
		UpdateWindow(hWnd);

        MSG msg; 
        ZeroMemory(&msg, sizeof(msg));
        while(msg.message != WM_QUIT)
        {
            if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
			else
			{
				// Update the main application.
                Mosaic.Update();
			}
        }
    }

	// Unregister the window class.
    UnregisterClass("Mosaic", wc.hInstance);
    return 0;
}

