
#include "CELoader.h"
#include "DUiMan.h"
#include "Viewer.h"

HWND      g_hwndApp;
HINSTANCE g_hinst;
CDUiMan   *g_pDUiMan = NULL;
CViewer   *g_pViewer = NULL;

WCHAR     g_wszAppName[] = TEXT("CELoader");

static BOOL AppInit(HINSTANCE hPrev,int nCmdShow);

BOOL InitObjects()
{
    g_pDUiMan = new CDUiMan();
    g_pViewer = new CViewer();

    g_pViewer->SetDUiMan(g_pDUiMan);

    // Initialize DirectDraw
    if ((g_pDUiMan->Initialize(g_hinst,g_hwndApp) != DD_OK) ||
        (g_pViewer->Initialize(g_hinst,g_hwndApp) != S_OK))
        return FALSE;

    return TRUE;
}

void DeleteObjects()
{
    delete g_pViewer;
    g_pViewer = NULL;
    delete g_pDUiMan;
    g_pDUiMan = NULL;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
    PROCESS_INFORMATION *pTempProcessInfo;
    if (g_pDUiMan)
    {
        g_pDUiMan->WndProc(hWnd,uMessage,wParam,lParam);
    }
    if (g_pViewer)
    {
        g_pViewer->WndProc(hWnd,uMessage,wParam,lParam);
    }

    switch (uMessage)
    {

    case WM_DESTROY:
        DeleteObjects();
        PostQuitMessage(0);
        return 0;
    case WM_SPAWNED_PROCESS:
        DeleteObjects();
        pTempProcessInfo = (PROCESS_INFORMATION *)wParam;
        WaitForSingleObject(pTempProcessInfo->hProcess,INFINITE);
        PostMessage(hWnd,WM_SHOWWINDOW,TRUE,0);
        free(pTempProcessInfo);
        InitObjects();
        break;
    } 

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


BOOL AppInit(HINSTANCE hPrev, int nCmdShow)
{
    WNDCLASS  cls;          

    if (!hPrev)
    {
        //  Register a class for the main application window
        cls.hCursor        = NULL;
        cls.hIcon          = NULL;
        cls.lpszMenuName   = NULL;
        cls.hbrBackground  = NULL;
        cls.hInstance      = g_hinst;
        cls.lpszClassName  = g_wszAppName;
        cls.lpfnWndProc    = (WNDPROC)WndProc;
        cls.style          = 0;
        cls.cbWndExtra     = 0;
        cls.cbClsExtra     = 0;

        if (!RegisterClass(&cls))
            return FALSE;
    }

    g_hwndApp = CreateWindowEx (0, g_wszAppName, g_wszAppName, WS_VISIBLE, 0, 0, 640, 480, NULL, NULL, g_hinst, NULL);

    InitObjects();

    return TRUE;
}

#ifdef _WIN32_WCE
extern "C" int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, WCHAR *lpCmdLine, int nCmdShow)
#else
extern "C" int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#endif 
{
    MSG msg;

    g_hinst = hInstance;

    if (!AppInit(hPrevInstance,nCmdShow))
        return 0;

    while (TRUE)
    {
        if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                break;

            TranslateMessage(&msg); 
            DispatchMessage(&msg);
        }
        else
        {
            if (g_pDUiMan)
                g_pDUiMan->UpdateFrame();
        }
    }

    return msg.wParam;
}
