/**
   @file Demo.cpp
   @author Morgan McGuire, morgan@cs.williams.edu
 */

#include "Demo.h"
#include "App.h"
#include "ImageAnalogy.h"

Demo::Demo(App* _app, const Settings& settings) : GApplet(_app), app(_app), settings(settings) {

    GConsole::Settings consoleSettings;
    consoleSettings.backgroundColor = Color3::green() * 0.1f;
    console = GConsole::create(app->debugFont, consoleSettings, staticConsoleCallback, this);
    
    // Start with the console disabled
    console->setActive(false);
    addModule(console);
}


void Demo::onInit()  {
    GApplet::onInit();

    Image3Ref A  = Image3::fromFile(settings.A, WRAP_CLAMP);
    Image3Ref A2 = Image3::fromFile(settings.A2, WRAP_CLAMP);
    Image3Ref B  = Image3::fromFile(settings.B, WRAP_CLAMP);

    resultImage = ImageAnalogy::compute(A, A2, B, settings.analogy);

    resultImage->save("out.png");

    exit(0);//TODO: remove
    setDesiredFrameRate(40.0f);
}


void Demo::onCleanup() {
    // Called when Demo::run() exits
  GApplet::onCleanup();
}


void Demo::onUserInput(UserInput* ui) {
    if (! console->active()) {
        // Only process immediate keys when the console is disabled
        if (ui->keyPressed(GKey::ESCAPE)) {
            console->setActive(true);
        }
    }
    GApplet::onUserInput(ui);
}


void Demo::onConsoleCommand(const std::string& command) {    
    TextInput t(TextInput::FROM_STRING, command);

    if (t.peek().type() == Token::SYMBOL) {
        std::string cmd = toLower(t.readSymbol());
        if (cmd == "exit") {
            app->endProgram = true;
        }
    } else {
        printHelp();
    }
}

void Demo::printHelp() {
}


void Demo::updateTexture(Image3Ref source, TextureRef& dest) {
    if ((source.notNull() && source->changed()) || dest.isNull()) {
        dest = Texture::fromMemory
            ("Image", Image3uint8::fromImage3(source)->getCArray(), TextureFormat::RGB8, source->width(), source->height(), 1,
             TextureFormat::RGB8, Texture::DIM_2D_NPOT, Texture::Settings::video());
        
        source->setChanged(false);
    }
}

void Demo::onGraphics(RenderDevice* rd) {
	
    rd->setColorClearValue(Color3::black());
    rd->clear();

    updateTexture(resultImage, resultTexture);
    if (resultTexture.notNull()) {
        rd->push2D();
            rd->setTexture(0, resultTexture);
            Draw::rect2D(resultTexture->rect2DBounds(), rd);
        rd->pop2D();
    }

    GApplet::onGraphics(rd);
}


