#pragma once

#include <QGeoCoordinate>
#include <QSharedPointer>
#include <QThread>

#include "geometry/geometry.h"
#include <atomic>
#include <condition_variable>
#include <functional>
#include <mutex>

// Aux structs
struct TransectInfo {
  TransectInfo(size_t n, bool r) : index(n), reversed(r) {}
  size_t index;
  bool reversed;
};

struct Route {
  geometry::FLineString path;
  std::vector<TransectInfo> info;
};

typedef std::vector<Route>
    Solution; // Every route corresponds to one run/vehicle

struct RoutingResult {
  geometry::LineStringArray transects;
  std::vector<Solution> solutionVector;
  std::string errorString;
};

struct RoutingParameter {
  RoutingParameter() : numSolutions(1), numRuns(1) {}
  geometry::FPolygon safeArea;
  std::size_t numSolutions;
  std::size_t numRuns;
};

//!
//! \brief The CSWorker class
//! \note Don't call QThread::start, QThread::quit, etc. onyl use Worker
//! members!
class RoutingThread : public QThread {
  Q_OBJECT
  using Lock = std::unique_lock<std::mutex>;

public:
  using PtrRoutingData = std::shared_ptr<RoutingResult>;
  using Work = std::function<bool(geometry::LineStringArray &)>;

  RoutingThread(QObject *parent = nullptr);
  ~RoutingThread() override;

  bool calculating() const;

public slots:
  void route(const RoutingParameter &par, const Work &work);

signals:
  void result(PtrRoutingData pTransects);
  void calculatingChanged();

protected:
  void run() override;

private:
  mutable std::mutex _mutex;
  mutable std::condition_variable _cv;
  // Internal data
  RoutingParameter _par;
  Work _work; // transect worker
  // State
  std::atomic_bool _calculating;
  std::atomic_bool _stop;
  std::atomic_bool _restart;
};
