#define Global

#ifdef WIN32
#    include <objidl.h>
#endif

#include "DLLRegister.h"
#include "File.h"
#include "Globals.h"
#include "Logging.h"
#include "Model3DList.h"
#include "TextureList.h"
#include "Thread.h"
#include "Timer.h"
#include "Window.h"

#ifdef WIN32
#    include <GdiPlus.h>
#    pragma comment(lib, "gdiplus.lib")
#    include "Mouse.h"
#    include "Window.h"
#else
#    include <unistd.h>
#endif

void Framework::initFramework(HINSTANCE__* hInst)
{
    if (isInitialized) return;
    currentThreadLockCount = 0;
#ifdef WIN32
    currentThreadId = GetCurrentThreadId();
#else
    currentThreadId = gettid();
#endif
    loggingHandler = new Logging::LoggingHandler();
    thRegister = new ThreadRegister();
#ifdef WIN32
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdiplusToken;
    Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, 0);
    msgExit = 0;
    MouseTrack = 1;
#endif
    for (int i = 0; i < 3; ++i)
        MouseState[i] = 0;
    dlls = new DLLRegister();
    _hinst = hInst;
    isInitialized = 1;
    debugDX = 0;
    cursorVisible = 1;
}

void Framework::releaseFramework()
{
    if (!isInitialized) return;
    thRegister->cleanUpClosedThreads();
    dlls->release();
    delete thRegister;
    loggingHandler->release();
    isInitialized = 0;
}

bool Framework::isThreadOk(Thread* t)
{
    return thRegister->isThread(t);
}

// Returns the thread register of the framework
Framework::ThreadRegister* Framework::getThreadRegister()
{
    return thRegister;
}

#ifdef WIN32

Framework::Point Framework::getMousePos()
{
    POINT point;
    GetCursorPos(&point);
    return {point.x, point.y};
}

//! Sets the mouse position on the screen
void Framework::setMousePos(const Point& pos)
{
    SetCursorPos(pos.x, pos.y);
}

#endif

bool Framework::getMouseState(int key)
{
    return MouseState[key];
}

bool Framework::getKeyState(unsigned char key)
{
#ifdef WIN32
    return GetKeyState(key) & 0x8000;
#else
    return 0;
#endif
}

// Returns the DLL register containing all currently dynamically loaded DLLs
Framework::DLLRegister* Framework::getDLLRegister()
{
    return Framework::dlls;
}

//! Sets DirectX to debug mode
void Framework::setDebugDX(bool debug)
{
    debugDX = debug;
}

#ifdef WIN32
// returns a reference to the mouse
Framework::Mouse& Framework::getMouse()
{
    return Framework::mousePointer;
}

//! sets the mouse state to visible or invisible
void Framework::setShowCursor(bool visible)
{
    CURSORINFO info = {0};
    info.cbSize = sizeof(CURSORINFO);
    GetCursorInfo(&info);
    if ((info.flags != 0) == (visible == 0)) ShowCursor(visible);
    cursorVisible = visible;
}

#endif