//
// FileName.cpp
//

// Engine includes.
#include "GameManager.h"
#include "LogManager.h"
#include "ResourceManager.h"
#include "WorldManager.h"

// Game includes.
#include "FileName.h"
#include "main.h"
#include "Message.h"

FileName::FileName(std::string filename) {

  // Convert filename to upper case.
  std::transform(filename.begin(), filename.end(), filename.begin(),
		 ::toupper);

  // Setup.
  setType(FILENAME_TYPE);
  setText(filename);
  setViewString("File name: ");
  setBorder(true);
  setLocation(df::CENTER_CENTER);
  setColor(df::WHITE);
  setLimit(FILENAME_LIMIT);

  // Unload any old sprite.
  RM.unloadSprite(SPRITE_LABEL);

  // Delete any HUD elements or player.
  df::ObjectList ol = WM.getAllObjects();
  df::ObjectListIterator oli(&ol);
  for (oli.first(); !oli.isDone(); oli.next()) {
    std::string type = oli.currentObject() -> getType();
    if (type == "player" ||
	type == "ColorButton" ||
	type == "LoadButton" ||
	type == "SlowdownButton" ||
	type == "Reticle" ||
	type == "Fraps"
	)
      WM.markForDelete(oli.currentObject());
  }
}

int FileName::eventHandler(const df::Event *p_e) {

  if (p_e->getType() == df::KEYBOARD_EVENT) {
    const df::EventKeyboard *p_ke =
      dynamic_cast <const df::EventKeyboard *> (p_e);
    if (p_ke -> getKey() == df::Keyboard::ESCAPE &&
        p_ke -> getKeyboardAction() == df::KEY_PRESSED) {
      LM.writeLog("Escape");
      GM.setGameOver();
      return 1;
    }
  }

  return TextEntry::eventHandler(p_e);
}

// On callback, set/reset.
void FileName::callback() {
  LM.writeLog("FileName::callback(): Filename: %s", getText().c_str());

  // Delete any old messages.
  df::ObjectList ol = WM.objectsOfType("Message");
  if (ol.getCount())
    WM.markForDelete(ol[0]);

  // Setup player with new sprite.
  if (setupPlayer(getText()) == 0) {

    WM.markForDelete(this);

  } else {

    new Message("Error! See 'dragonfly.log'");
    LM.flush();

  }
}
