#pragma once

#include "mission/mission_store.hpp"

#include <atomic>
#include <functional>
#include <mutex>
#include <string>
#include <thread>

namespace lm {

class MissionScheduler
{
public:
  using EnqueueFn = std::function<bool(const nlohmann::json& request, std::string& err)>;

  MissionScheduler(MissionStore& store, EnqueueFn enqueue_fn);
  ~MissionScheduler();

  MissionScheduler(const MissionScheduler&) = delete;
  MissionScheduler& operator=(const MissionScheduler&) = delete;

  bool runScheduleNow(const std::string& id, std::string& err);

private:
  MissionStore& store_;
  EnqueueFn enqueue_fn_;

  std::atomic<bool> stop_{false};
  std::thread worker_;

  void workerLoop();
  bool queueSchedule(const nlohmann::json& schedule, std::string& err);
  void markQueued(const std::string& id);
};

}  // namespace lm
