#include "gui_fsm.hpp"
#include <iostream>
#include <chrono>
#include <numeric>
#include <functional>
#include "components.hpp"
#include <numbers>
#include "systems.hpp"
#include "events.hpp"
#include "sound.hpp"
#include <fmt/xchar.h>
#include "arena_fsm.hpp"

namespace arena {
  using namespace components;

  FSM::FSM(std::string enemy_name) :
    $enemy_name(enemy_name),
    $window(sf::VideoMode({SCREEN_WIDTH, SCREEN_HEIGHT}), "Arena Battle Tester"),
    $font{FONT_FILE_NAME}
    {
    }

  void FSM::event(Event ev) {
    switch($state) {
      FSM_STATE(State, START, ev);
      FSM_STATE(State, IDLE, ev);
      FSM_STATE(State, END, ev);
    }
  }

  void FSM::START(Event ) {
    run_systems();
    $level = $level_mgr.current();

    auto entity_id = $level_mgr.spawn_enemy($enemy_name);

    $arena_ui = make_shared<ArenaUI>($level.world, entity_id);
    $arena_ui->init();
    state(State::IDLE);
  }

  void FSM::END(Event ev) {
    dbc::log(fmt::format("END: received event after done: {}", int(ev)));
  }

  void FSM::IDLE(Event ev) {
    using enum Event;

    switch(ev) {
      case QUIT:
        $window.close();
        state(State::END);
        return; // done
      case CLOSE:
        dbc::log("Nothing to close.");
        break;
      case TICK:
        // do nothing
        break;
      case ATTACK:
        dbc::log("ATTACK!");
        break;
      default:
        dbc::sentinel("unhandled event in IDLE");
    }
  }

  void FSM::keyboard_mouse() {
    while(const auto ev = $window.pollEvent()) {
      if(ev->is<sf::Event::Closed>()) {
        event(Event::QUIT);
      }

      if(const auto* mouse = ev->getIf<sf::Event::MouseButtonPressed>()) {
        if(mouse->button == sf::Mouse::Button::Left) {
          sf::Vector2f pos = $window.mapPixelToCoords(mouse->position);
          (void)pos;
        }
      }

      if(const auto* key = ev->getIf<sf::Event::KeyPressed>()) {
        using KEY = sf::Keyboard::Scan;

        switch(key->scancode) {
          case KEY::Escape:
            event(Event::CLOSE);
            break;
          case KEY::Space:
            event(Event::ATTACK);
            break;
          default:
            break; // ignored
        }
      }
    }
  }

  void FSM::draw_gui() {
    if($arena_ui != nullptr) {
      $arena_ui->render($window);
    }
  }

  void FSM::render() {
    $window.clear();
    draw_gui();
    $window.display();
  }

  void FSM::run_systems() {
  }

  bool FSM::active() {
    return !in_state(State::END);
  }

  void FSM::handle_world_events() {
  }
}
