////////////////////////////////////////////////////////////////////////////////
// Window.cpp
//
//  Window-handling code

#include "stdhdr.h"

#include "Debug.h"
#include "Sound.h"
#include "Input.h"
#include "Window.h"

////////////////////////////////////////////////////////////////////////////////
// Window handling

HWND hWndMain;

// TRUE if our application is active
BOOL    g_bActive = FALSE;

// Handle all messages for the main window.
LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CLOSE:
        OnClose();
        DestroyWindow(hWnd);
        return 0;

    // Clear the cursor while active.
    case WM_SETCURSOR:
        SetCursor(NULL);
        return 0;

    case WM_ACTIVATE:
        if (LOWORD(wParam) == WA_INACTIVE)
        {
            TRACE0("Deactivating...\n");
            g_bActive = FALSE;
            UnacquireDevices();
            StopBackgroundMusic();
        }
        else
        {
            TRACE0("Activating...\n");
            g_bActive = TRUE;
            AcquireDevices();
            PlayBackgroundMusic();
        }
        return 0;

    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

// Register the window class for the main window.
void RegisterWindowClass()
{
    WNDCLASSEX  wcx;

    ZeroMemory(&wcx, sizeof(WNDCLASSEX));
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.lpfnWndProc = MainWindowProc;
    wcx.hInstance = GetModuleHandle(NULL);
    // Windows-default icon. Replace with your own.
    wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wcx.hCursor = NULL;
    // Black background for the window.
    wcx.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wcx.lpszMenuName = NULL;
    wcx.lpszClassName = "SampleWindowClass";
    RegisterClassEx(&wcx);
}

BOOL InitWindow(LPCTSTR lpTitle)
{
    RegisterWindowClass();

    // Create a window that fills the screen.
    hWndMain = CreateWindowEx(WS_EX_APPWINDOW,
        "SampleWindowClass", lpTitle, WS_POPUP,
        0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
        NULL, NULL, GetModuleHandle(NULL), NULL);
    if (hWndMain == NULL)
    {
        DISPLAYERROR("Could not create window.");
        return FALSE;
    }
    
    return TRUE;
}

void Run()
{
    MSG msg;

    // Message loop. Note that this has been modified to allow
    //  us to execute even if no messages are being processed.
    for (;;)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
        {
            if (!GetMessage(&msg, NULL, 0, 0))
                break;
            
            // If you want WM_CHAR messages, add
            //  TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        
        // Idle-time processing
        OnIdle();
    }
}