#ifndef LIB94_BENCH_BENCH_WINDOW_HPP
#define LIB94_BENCH_BENCH_WINDOW_HPP

#include <gtkmm.h>
#include <thread>

#include "core_widget.hpp"

class bench_window : public Gtk::Window {
public:
  bench_window();

  Glib::Dispatcher runner_update_ui_dispatcher;
  Glib::Dispatcher runner_stopping_dispatcher;

  bool runner_stop_now;
  bool runner_stop_on_death;
  bool runner_stop_on_win;
  bool runner_hyperspeed;

  core_widget core;

private:
  class warrior_list_columns_record : public Gtk::TreeModelColumnRecord {
  public:
    Gtk::TreeModelColumn<Glib::ustring> warrior_name;
    Gtk::TreeModelColumn<size_t> processes;
    Gtk::TreeModelColumn<Glib::ustring> next_pc;
    Gtk::TreeModelColumn<const lib94::warrior *> warrior;
  
    warrior_list_columns_record() {
      add(warrior_name);
      add(processes);
      add(next_pc);
      add(warrior);
    }
  };

  class instructions_columns_record : public Gtk::TreeModelColumnRecord {
  public:
    Gtk::TreeModelColumn<lib94::number_t> address;
    Gtk::TreeModelColumn<Glib::ustring> instruction;

    instructions_columns_record() {
      add(address);
      add(instruction);
    }
  };

  Gtk::ScrolledWindow warrior_list_scroll;
  Gtk::ScrolledWindow instructions_scroll;

  warrior_list_columns_record warrior_list_columns;
  instructions_columns_record instructions_columns;

  Glib::RefPtr<Gtk::TreeStore> warrior_list_store;
  Glib::RefPtr<Gtk::TreeStore> instructions_store;

  Gtk::TreeView warrior_list_view;
  Gtk::TreeView instructions_view;

  std::set<lib94::number_t> modified_addresses_for_instructions_view;

  void add_modified_for_instruction_view(std::set<lib94::number_t> the_set);

  Gtk::Box main_box;
  Gtk::Box control_box;

  Gtk::Button new_round_button;
  Gtk::Button single_step_button;
  Gtk::Button start_button;
  Gtk::Button stop_button;

  Gtk::CheckButton hyperspeed_toggle;
  Gtk::CheckButton pause_on_death_toggle;
  Gtk::CheckButton pause_on_win_toggle;

  Gtk::Label target_core_rate_label;
  Gtk::Scale target_core_rate_scale;

  Gtk::Button add_warrior_button;
  Gtk::Button remove_warrior_button;

  std::chrono::system_clock::time_point last_core_step_start;
  std::chrono::nanoseconds last_core_step_distance;
  Gtk::Label core_rate_label;
  Gtk::Label core_render_label;

  const lib94::warrior *do_step();
  void runner_main();

  void on_click_new_round();
  void on_click_single_step();
  void on_click_start();
  void on_click_stop();

  void on_toggle_hyperspeed();
  void on_toggle_pause_on_death();
  void on_toggle_pause_on_win();

  void on_target_core_rate_changed();

  void on_click_add_warrior();
  void on_click_remove_warrior();

  std::thread runner;
  bool runner_active;

  void update_buttons();
  void update_ui();

  void on_runner_stopping();

  void on_add_warrior_dialog_response(int response_id, Gtk::FileChooserDialog *dialog);
};

#endif