
#include <WFX/lang/WFXGUIApplication.h>
#include <WFX/lang/WFXSystem.h>

using namespace WFX;
using namespace WFX::lang;
using namespace WFX::io;
using namespace std;

WFXGUIApplication::WFXGUIApplication() {
    init();
}

WFXGUIApplication::WFXGUIApplication(int argc, char *argv[]) : WFXApplication(argc, argv) {
    init();
}

void WFXGUIApplication::setup(Int ww, Int wh, Int wd, std::string wt) {
    //create render window
    Window = SYS.getRenderWindow(ww, wh, wd, wt, false);
    //Renderer
    Renderer = SYS.getRenderer();
    //TextuerManager
    TextureManager = SYS.getTextureManager();
    //MaterialManager
    MaterialManager = new WFX::scene::MaterialManager();
    //create InputHandler and register as listener
    InputHandler = SYS.getInputHandler();
    InputHandler->flushEvents();
    Kernel->addTask(InputHandler);
    InputHandler->addKeyboardListener(this);
    //TimeTask
    TimeTask = SYS.getTimeTask();
    Kernel->addTask(TimeTask);
    //add app to kernel
    Kernel->addTask(this);
}

WFXGUIApplication::~WFXGUIApplication() {
    //TODO: check whether it is a good idea to delete the Singletons at this stage...
    delete Kernel;
    delete MaterialManager;
}

void WFXGUIApplication::init() {
    ScreenShotBase = "screen_";
    ScreenShotExt = "tga";
    //create necessary singletons
    //Kernel
    Kernel = new WFX::kernel::Kernel();
}

void WFXGUIApplication::run() {
    WFXApplication::run();
    Kernel->exec();
}

void WFXGUIApplication::exit() {
    WFXApplication::exit();
    Kernel->removeAllTasks();
}

void WFXGUIApplication::saveScreenShot() {
    UInt count = 0;
    Char ext[10];
    string fn;
    bool found = false;
    while (!found) {
        fn = "";
        sprintf(ext, "%04d.", count);
        fn += ScreenShotBase;
        fn += ext;
        fn += ScreenShotExt;
        File f(fn);
        if (!f.isFile())
            found = true;
        count++;
        if (count > 9998) 
            found = true;
    }
    Window->saveToFile(File(fn));
}

