/**
 @file DApp.h

 Dojo Game Engine

 Copyright 2005, Morgan McGuire
 All rights reserved.
 */
#include "dojo/DApp.h"

namespace dojo {

DApp* app = NULL;

DApp::DApp(const GAppSettings& settings, GWindow* window) : GApp(settings, window), currentApplet(NULL) {
    audioDevice = new AudioDevice();    
    audioDevice->init();

    m_desiredFrameRate = 65;
    m_paused = true;
    m_singleStep = false;

    m_simTimeRate = 1;

    hudUI.loadData(this, debugFont);
    debugShowRenderingStats = false;
    debugShowText = false;
}


DApp::~DApp() {
    delete audioDevice;
    audioDevice = NULL;
}


void DApp::setApplet(class DApplet* a) {
    currentApplet = a;
    a->setDesiredFrameRate(m_desiredFrameRate);
    debugSetPaused(m_paused);
}


void DApp::debugSetPaused(bool p) {
    m_paused = p;

    if (currentApplet) {
        if (m_paused) {
            currentApplet->setSimTimeRate(0);
        } else {
            currentApplet->setSimTimeRate(m_simTimeRate);
        }
    }
}

void DApp::debugSetSingleStep(bool s) {
    m_singleStep = s;

    if (s) {
        debugSetPaused(false);
    }
}

////////////////////////////////////////////////////////////////////////

void DApplet::onInit() {
    GApplet::onInit();
}

void DApplet::onCleanup() {
    GApplet::onCleanup();
}

void DApplet::onGraphics(RenderDevice* rd) {
    app->hudUI.onGraphics(rd);
}

void DApplet::onUserInput(UserInput* ui) {
    app->hudUI.onUserInput(ui);

    if (ui->keyPressed(SDLK_F8)) {
        World::world()->renderMode = (World::RenderMode)((World::world()->renderMode + 1) % World::RENDER_MAX);
    }

    if (ui->keyPressed(SDLK_F5)) {
        app->debugSetPaused(! app->debugPaused());
    }

    if (ui->keyPressed(SDLK_F10)) {
        app->debugSetSingleStep(true);
    }
}

void DApplet::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) {
	// Add physical simulation here.  Run off the ideal timer.
    World::world()->onSimulation(idt);

    if (app->debugSingleStep()) {
        app->debugSetSingleStep(false);
        app->debugSetPaused(true);
    }
}

}
