#pragma once

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

#include "snake.h"
#include <atomic>
#include <condition_variable>
#include <mutex>

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

public:
  using Route = QList<QGeoCoordinate>;
  using PtrRoute = QSharedPointer<Route>;

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

  bool calculating();

public slots:
  void update(const QList<QGeoCoordinate> &polygon,
              const QGeoCoordinate &origin, snake::Length deltaR,
              snake::Length minLength, snake::Angle deltaAlpha);
  void update(const QGeoCoordinate &depot,
              const QList<QGeoCoordinate> &safeArea,
              const QList<QGeoCoordinate> &polygon,
              const QGeoCoordinate &origin, snake::Length deltaR,
              snake::Length minLength, snake::Angle deltaAlpha);

signals:
  void ready(PtrRoute pTransects);
  void calculatingChanged();

protected:
  void run() override;

private:
  mutable std::mutex _mutex;
  mutable std::condition_variable _cv;
  // Internal data
  QGeoCoordinate _depot;
  QList<QGeoCoordinate> _safeArea;
  QList<QGeoCoordinate> _polygon;
  QGeoCoordinate _origin;
  snake::Length _deltaR;
  snake::Angle _deltaAlpha;
  snake::Length _minLength;
  std::size_t _maxWaypoints;

  // State
  std::atomic_bool _useDepotSafeArea;
  std::atomic_bool _calculating;
  std::atomic_bool _stop;
  std::atomic_bool _restart;
};
