#include "factory/application/simulation_service.h"
#include <chrono>
#include <stdexcept>

namespace factory {
SimulationService::~SimulationService() { stop(); }
void SimulationService::start(Project project, bool playing) {
  auto prepared = std::make_unique<Simulation>(std::move(project));
  stop();
  {
    std::lock_guard lock(mutex_);
    simulation_ = std::move(prepared);
    playing_ = playing;
  }
  worker_ = std::jthread([this](const std::stop_token& token) {
    std::unique_lock lock(mutex_);
    while (!token.stop_requested()) {
      if (!playing_) {
        wake_.wait(lock, token, [this] { return playing_; });
        continue;
      }
      const bool interrupted = wake_.wait_for(lock, token, std::chrono::milliseconds(100 / speed_),
                                              [this] { return !playing_; });
      if (token.stop_requested())
        break;
      if (interrupted)
        continue;
      simulation_->step();
      if (simulation_->snapshot().outcome != Outcome::Running)
        playing_ = false;
    }
  });
}
void SimulationService::stop() {
  if (worker_.joinable()) {
    worker_.request_stop();
    wake_.notify_all();
    worker_.join();
  }
  std::lock_guard lock(mutex_);
  simulation_.reset();
  playing_ = false;
}
void SimulationService::setPlaying(bool playing) {
  {
    std::lock_guard lock(mutex_);
    playing_ = playing && simulation_ && simulation_->snapshot().outcome == Outcome::Running;
  }
  wake_.notify_all();
}
bool SimulationService::playing() const {
  std::lock_guard lock(mutex_);
  return playing_;
}
bool SimulationService::active() const {
  std::lock_guard lock(mutex_);
  return simulation_ != nullptr;
}
void SimulationService::setSpeed(int speed) {
  if (speed != 1 && speed != 2 && speed != 4)
    throw std::invalid_argument("Speed must be 1, 2 or 4");
  std::lock_guard lock(mutex_);
  speed_ = speed;
}
void SimulationService::stepOnce() {
  std::lock_guard lock(mutex_);
  if (simulation_ && !playing_)
    simulation_->step();
}
Snapshot SimulationService::snapshot() const {
  std::lock_guard lock(mutex_);
  return simulation_ ? simulation_->snapshot() : Snapshot{};
}
} // namespace factory
