#include "gui.hpp"
#include <stdlib.h>                   // for EXIT_SUCCESS
#include <chrono>                     // for milliseconds
#include <fmt/core.h>
#include <memory>                  // for allocator, shared_ptr
#include <string>                  // for operator+, to_string
#include <vector>
#include <SFML/Audio.hpp>
#include <nlohmann/json.hpp>
#include "builder.hpp"
#include <fstream>
#include <iostream>

using std::string, std::vector;

using namespace nlohmann;
namespace fs = std::filesystem;

GUI::GUI(SFMLBackend &backend) : gui(backend) {
  std::ifstream infile(".tarpit.json");
  json data = json::parse(infile);

  // json load the config file
  you_died_sound.load(data, "you_died");
  build_success_sound.load(data, "build_success");
  build_failed_sound.load(data, "build_failed");
  building_sound.load(data, "building", true);
}

void GUI::output(const string msg) {
  // _lines.push_back(msg);
  std::cout << msg << std::endl;
}

void GUI::main_loop() {
  gui.handle_events();
  gui.update_entities();
  gui.update_log(_lines);
}

void GUI::build_success() {
  gui.change_face("build_success");
  building_sound.stop();
  build_success_sound.play();
  output("BUILD FINISHED!");
}

void GUI::build_failed(bool play_sound, const string &command) {
  gui.change_face("build_failed");
  building_sound.stop();

  if(play_sound) {
    build_failed_sound.play();
  }

  output(fmt::format("!!! BUILD FAILED. Your command correct? '{}'", command));
}

void GUI::you_died() {
  gui.change_face("you_died");
  building_sound.stop();
  you_died_sound.play();
  output("!!!! YOU DIED! !!!! Learn to code luser.");
  output("YOU DIED!");
}

void GUI::building() {
  gui.change_face("building");
  output("############# START ############");
  output(">>>> Will it Build?");
  building_sound.play();
}