#include "stdafx.h"
#include "MainGame.h"

MainGame::MainGame()
{
    g_pLogManager->Setup("\\Log\\");
    g_pLogManager->WriteLog(EL_INFO, "MainGame constructor");
    g_pKeyManager->Setup();
    g_pDbManager->Setup();

    MouseLock();
    Start();
}


MainGame::~MainGame()
{
    g_pLogManager->WriteLog(EL_INFO, "MainGame destructor");
    Release();
}

void MainGame::Start()
{
    g_pScnManager->AddScene("splash", new SplashScene);
    g_pScnManager->AddScene("game", new GameScene);

    g_pScnManager->ChangeScene("splash");
}

void MainGame::Update()
{
    SystemController();
    
    g_pScnManager->Update();

    GameNode::Update();
}

void MainGame::Render()
{
    PAINTSTRUCT ps;
    HDC hdc;
    hdc = BeginPaint(g_hWnd, &ps);

    PatBlt(g_hDC, 0, 0, W_WIDTH, W_HEIGHT, WHITENESS);

    g_pScnManager->Render();
    g_pTimerManager->Render();
    m_pImgBackBuffer->FastRender(hdc);
    
    EndPaint(g_hWnd, &ps);
}

void MainGame::SystemController()
{
    if (g_pKeyManager->isOnceKeyDown(VK_ESCAPE))
    {
        PostQuitMessage(0);
    }

    //  Ctrl + Alt 키 조합으로 마우스 가두기 해제
    if (g_pKeyManager->isStayKeyDown(VK_CONTROL))
    {
        if (g_pKeyManager->isOnceKeyDown(VK_MENU))
        {
#ifdef _DEBUG
#else
            MouseUnlock();
#endif // _DEBUG
        }
    }

    if (g_pKeyManager->isOnceKeyDown(VK_LBUTTON))
    {
#ifdef _DEBUG
#else
        MouseLock();    //  창 내부 클릭 시 마우스 가두기
#endif // _DEBUG
    }
}

void MainGame::MouseLock()
{
    RECT Rt;
    GetWindowRect(g_hWnd, &Rt);
    if (PtInRect(&Rt, g_ptMouse))
        ClipCursor(&Rt);
}

void MainGame::MouseUnlock()
{
    ClipCursor(NULL);
}

void MainGame::Release()
{
    //  KeyManager release
    g_pKeyManager->ReleaseInstance();
    //  LogManager release
    g_pLogManager->ReleaseInstance();
    //  ImageManager release
    g_pImgManager->ReleaseAll();
    g_pImgManager->ReleaseInstance();
    //  DrawHelper release
    g_pDrawHelper->ReleaseInstance();
    //  GeometryHelper release
    g_pGeoHelper->ReleaseInstance();
    //  TimerManager release
    g_pTimerManager->DeleteTimerAll();
    g_pTimerManager->ReleaseInstance();
    //  DbManager release
    g_pDbManager->SelfDestroy();
    g_pDbManager->ReleaseInstance();
    //  SceneManager release
    g_pScnManager->ReleaseAll();
}
