//
// functions.cpp
//

// System includes.
#include <stdlib.h>

// Engine includes.
#include "DisplayManager.h"
#include "LogManager.h"
#include "Fraps.h"
#include "ResourceManager.h"
#include "WorldManager.h"

// Game includes.
#include "ColorButton.h"
#include "FileName.h"
#include "functions.h"
#include "LoadButton.h"
#include "main.h"
#include "Player.h"
#include "Reticle.h"
#include "SlowdownButton.h"

// Load resources and setup player with sprite and buttons.
// Return 0 if ok, else -1.
int setupPlayer(std::string sprite_filename) {

  std::string s = sprite_filename;

  // Convert filename to lower case.
  std::transform(s.begin(), s.end(), s.begin(), ::tolower);

  // Load sprite.
  if (RM.loadSprite(s.c_str(), SPRITE_LABEL) == -1) {
    LM.writeLog("setupPlayer():: Error!  Unable to load sprite '%s'.",
		s.c_str());
    return -1;
  }

  // Resize screen to fit sprite.
  int width = RM.getSprite(SPRITE_LABEL) -> getWidth();
  int height = RM.getSprite(SPRITE_LABEL) -> getWidth();
  DM.setHorizontal(width + 26);
  DM.setVertical(height + 6);
  df::Box boundary(df::Vector(0,0),
		   (float) DM.getHorizontal(),
		   (float) DM.getVertical());
  WM.setBoundary(boundary);
  WM.setView(boundary);

  // Create Player to play sprite.
  if (! new Player) {
    LM.writeLog("setupPlayer():: Error!  Unable to create Player.");
    return -1;
  }
  
  // Create HUD buttons.
  if (!(new LoadButton(sprite_filename))) {
    LM.writeLog("setupPlayer():: Error!  Unable to create LoadButton.");
    return -1;
  }
  if (! (new ColorButton(RM.getSprite(SPRITE_LABEL)))) {
    LM.writeLog("setupPlayer():: Error!  Unable to create ColorButton.");
    return -1;
  }
  if (!(new SlowdownButton(RM.getSprite(SPRITE_LABEL)))) {
    LM.writeLog("setupPlayer():: Error!  Unable to create SlowdownButton.");
    return -1;
  }

  // Other
  if (!(new Reticle)) {
    LM.writeLog("setupPlayer():: Error!  Unable to create Reticle.");
    return -1;
  }
  new df::Fraps;

  // All is well.
  return 0;
}

// Print usage message and quit.
void usage() {
  fprintf(stderr, "sprite-player (%.1f) - play Dragonfly sprites\n", VERSION);
  fprintf(stderr, "  usage: sprite-player [-h] {filename}\n");
  fprintf(stderr, "         filename - sprite to load and play\n");
  fprintf(stderr, "         -h this help message\n");
  exit(1);
}
