/*
* Copyright (C) 2004 TES Electronic Solutions GmbH,
* All Rights Reserved.
* This source code and any compilation or derivative thereof is the
* proprietary information of TES Electronic Solutions GmbH
* and is confidential in nature.
* Under no circumstances is this software to be exposed to or placed
* under an Open Source License of any type without the expressed
* written permission of TES Electronic Solutions GmbH
*
*############################################################
*/

#include "StreamRuntimeStartup.h"
#include "GUIAutoPtr.h"
#include "GUI.h"

#include <shellapi.h> // for CommandLineToArgv

#include "GUIResourceFileHandler.h"

#include "GUIMemLeakDetection.h"
#include "GUIMemLeakWatcher.h"

int WINAPI WinMain(
    IN HINSTANCE hInstance,
    IN HINSTANCE hPrevInstance,
    IN LPSTR lpCmdLine,
    IN int nShowCmd)
{
    NStreamRuntime::CStreamRuntimeStartup kStreamRuntime;

    // convert commandline into eC_String
    LPWSTR *szArglist;
    int nArgs;
    eC_String *argv = NULL;

    szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
    if (nArgs > 0)
    {
        argv = new eC_String[nArgs];
        for (int i = 0; i < nArgs; ++i)
        {
            argv[i] = eC_String(szArglist[i]);
        }
    }
    LocalFree(szArglist);

    kStreamRuntime.ProcessCommandLine(nArgs, argv);
    delete[] argv;

    //GETRESHANDLER.SetFileOpenOrder(CGUIResourceFileHandler::RESOURCE_FILE_FIRST);
    //GETRESHANDLER.SetResourceFile("Resources.dat", true);

    //GETRESHANDLER.SetFileOpenOrder(CGUIResourceFileHandler::RESOURCE_FILE_FIRST);
    //GETRESHANDLER.SetResourceData(GUIResourceData);

    kStreamRuntime.LoadLicenseFile();

    try
    {
        // Load configuration (e.g. ScreenSize, initial Dialog etc.) from file
        if (!kStreamRuntime.LoadConfiguration())
        {
            return 0; // Failed to load configuration file.
        }

        // Initialize the application window
        kStreamRuntime.Init(hInstance, nShowCmd);
        // Initialize platform specific wrappers for Graphics, Fonts, Input etc. 
        kStreamRuntime.ConstructWrapperClasses();

        // create and run GUI
        kStreamRuntime.CreateGUI();
    }
    catch (...)
    {
        MessageBox(
            NULL,
            TEXT("StreamRuntime performed a clean shutdown after an exception was caught. \nPlease check StreamRuntime.log for further details on the problem."),
            TEXT("StreamRuntime encountered a problem"),
            0);
    }

    // Shutdown and clean up
    kStreamRuntime.DestructWrapperClasses();
    kStreamRuntime.DeInit();

    return 0;
}
