#pragma once

#include <QFutureWatcher>
#include <QJsonArray>
#include <QVector>
#include <memory>

#include "ComplexMissionItem.h"
#include "QGCQGeoCoordinate.h"
#include "SettingsFact.h"

#include "AreaData.h"
#include "ProgressArray.h"

class RoutingThread;
class RoutingResult;

namespace routing {
class GeneratorBase;
}

class MeasurementComplexItem : public ComplexMissionItem {
  Q_OBJECT

  using PtrGenerator = routing::GeneratorBase *;
  using PtrAreaData = AreaData *;
  using PtrRoutingData = std::shared_ptr<RoutingResult>;
  using PtrWorker = RoutingThread *;
  using Variant = QVariantList;

  enum class STATE { IDLE, ROUTING, EDITING };

public:
  MeasurementComplexItem(PlanMasterController *masterController, bool flyView,
                         const QString &kmlOrShpFile, QObject *parent);
  ~MeasurementComplexItem();

  Q_PROPERTY(Fact *variantIndex READ variantIndex CONSTANT)
  Q_PROPERTY(Fact *altitude READ altitude CONSTANT)
  Q_PROPERTY(
      QStringList variantNames READ variantNames NOTIFY variantNamesChanged)
  Q_PROPERTY(QStringList generatorNameList READ generatorNameList NOTIFY
                 generatorListChanged)
  Q_PROPERTY(bool calculating READ calculating NOTIFY calculatingChanged)
  Q_PROPERTY(bool editing READ editing NOTIFY editingChanged)
  Q_PROPERTY(bool holdProgress READ holdProgress WRITE setHoldProgress NOTIFY
                 holdProgressChanged)
  Q_PROPERTY(bool idle READ idle NOTIFY idleChanged)
  Q_PROPERTY(
      routing::GeneratorBase *generator READ generator NOTIFY generatorChanged)
  Q_PROPERTY(int generatorIndex READ generatorIndex NOTIFY generatorChanged)
  Q_PROPERTY(AreaData *areaData READ areaData NOTIFY areaDataChanged)
  Q_PROPERTY(QVariantList route READ route NOTIFY routeChanged)

  Q_INVOKABLE void reverseRoute(void);

  // Overrides from ComplexMissionItem
  virtual QString patternName(void) const override final;
  virtual double complexDistance(void) const override final;
  virtual int lastSequenceNumber(void) const final;
  virtual bool load(const QJsonObject &complexObject, int sequenceNumber,
                    QString &errorString) override final;
  virtual double
  greatestDistanceTo(const QGeoCoordinate &other) const override final;
  virtual QString mapVisualQML(void) const override final;

  // Overrides from VisualMissionItem
  virtual bool dirty(void) const override final;
  virtual bool isSimpleItem(void) const override final;
  virtual bool isStandaloneCoordinate(void) const override final;
  virtual bool specifiesCoordinate(void) const override final;
  virtual bool specifiesAltitudeOnly(void) const override final;
  virtual QGeoCoordinate coordinate(void) const override final;
  virtual QGeoCoordinate exitCoordinate(void) const override final;
  virtual int sequenceNumber(void) const override final;
  virtual double specifiedFlightSpeed(void) final override;
  virtual double specifiedGimbalYaw(void) final override;
  virtual double specifiedGimbalPitch(void) final override;
  virtual void appendMissionItems(QList<MissionItem *> &items,
                                  QObject *missionItemParent) final override;
  virtual void setMissionFlightStatus(
      const MissionController::MissionFlightStatus_t &missionFlightStatus)
      final override;
  virtual void applyNewAltitude(double newAltitude) override final;
  virtual double additionalTimeDelay(void) const override final;
  virtual ReadyForSaveState readyForSaveState(void) const override final;
  virtual bool exitCoordinateSameAsEntry(void) const override final;
  virtual void setDirty(bool dirty) override final;
  virtual void setCoordinate(const QGeoCoordinate &coordinate) override final;
  virtual void setSequenceNumber(int sequenceNumber) override final;
  virtual void save(QJsonArray &missionItems) override final;
  virtual double amslEntryAlt(void) const override final;
  virtual double amslExitAlt(void) const override final;
  virtual double minAMSLAltitude(void) const override final;
  virtual double maxAMSLAltitude(void) const override final;
  virtual QString commandDescription(void) const override final;
  virtual QString commandName(void) const override final;
  virtual QString abbreviation(void) const override final;

  // Generator
  //!
  //! \brief addGenerator Adds a generator.
  //!
  //! Adds a generator. The generator will be added to the generatorList() and
  //! it's name to the generatorNameList(). Generators are identified by index
  //! or name(), hence their name must be unique. A generator can not be added
  //! if name() is already inside generatorNameList(). \param g Pointer to a
  //! generator. \return Returns true if the generator was addes successfully,
  //! false either.
  //!
  bool addGenerator(routing::GeneratorBase *g);
  //!
  //! \brief removeGenerator Removes the generator.
  //! \param name The name of the generator to be removed.
  //! \return Returns true if the generator was removed successfully.
  //! \note The generator will be deleted if this or nullptr is it's parent.
  bool removeGenerator(const QString &name);
  //!
  //! \brief removeGenerator Removes the generator.
  //! \param index The index of the generator to be removed
  //! \return Returns true if the generator was removed successfully.
  //! \note See above.
  bool removeGenerator(int index);

  Q_INVOKABLE bool switchToGenerator(const QString &name);
  Q_INVOKABLE bool switchToGenerator(int index);
  //!
  //! \brief resetGenerators Resets the generators as they where after creation
  //! of this object.
  //!
  Q_INVOKABLE void resetGenerators();

  QList<PtrGenerator> generatorList() const;
  QStringList generatorNameList() const;

  routing::GeneratorBase *generator();
  const routing::GeneratorBase *generator() const;
  routing::GeneratorBase *generator(int index);
  const routing::GeneratorBase *generator(int index) const;
  //!
  //! \brief generatorIndex
  //! \return Returns the index of the current generator.
  int generatorIndex() const;
  //!
  //! \brief generatorIndex
  //! \param name
  //! \return Returns the index of the generator with the name \p name, or -1 if
  //! the generator is unknown.
  //!
  int generatorIndex(const QString &name);

  // Editing.
  //!
  //! \brief startEditing Starts area data editing.
  //!
  //! Starts area data editing. Route will not be updated bewteen a call
  //! sequence of editingStart() and editingStop().
  //!
  Q_INVOKABLE void startEditing();
  //!
  //! \brief stopEditing Stops area editing.
  //!
  //! Stops area editing. Will reset area data to the state before
  //! editingStart() if it is invalid. Triggers a route update.
  //!
  //! \param doUpdate No route update will be triggered if false, route update
  //! will eventually be triggered if true.
  //!
  //!  \return Returns true if a route
  //! update was triggered, false either.
  //!
  Q_INVOKABLE bool stopEditing(bool doUpdate = true);
  //!
  //! \brief abortEditing Aborts area editing.
  //!
  //! Will reset area data to the state before
  //! editingStart().
  //!
  Q_INVOKABLE void abortEditing();
  //!
  //! \brief reset Resets the areas to the state before startEditing().
  //!
  //! Resets the areas to the state before startEditing(). Does nothing if
  //! editinge() == false.
  //!
  Q_INVOKABLE void reset();

  //!
  //! \brief initialize Initializes the areas in a valid way, such that they
  //! area inside the bounding box. \param bottomLeft bottom left corner of the
  //! bounding box. \param topRight  top right corner of the bounding box. \note
  //! Behavior is undefined, if \p bottomLeft and \p topRight are not the bottom
  //! left and the top right corner of the bounding box. \return Returns true on
  //! succes, false either.
  //!
  Q_INVOKABLE bool initialize(const QGeoCoordinate &bottomLeft,
                              const QGeoCoordinate &topRight);
  //!
  //! \brief initialized Checks if area data is initialized
  //! \return Returns true if area list contains a SafeArea and a
  //! MeasurementArea and both areas have at least three vertices, returns false
  //! either.
  //!
  Q_INVOKABLE bool initialized();

  // Property getters
  const AreaData *areaData() const;
  AreaData *areaData();
  QVariantList route();

  Fact *variantIndex();
  QStringList variantNames() const;
  Fact *altitude();

  bool calculating() const;
  bool editing() const; // set to true on creation
  bool idle() const;
  bool followTerrain() const;

  static const char *settingsGroup;
  static const char *jsonComplexItemTypeValue;
  static const QString name;

  bool holdProgress() const;
  void setHoldProgress(bool holdProgress);

signals:
  void variantNamesChanged();

  void generatorListChanged();
  void generatorChanged();

  void calculatingChanged();
  void editingChanged();
  void idleChanged();

  void areaDataChanged();
  void routeChanged();
  void holdProgressChanged();

private slots:

  // Worker functions.
  void _storeRoutingData(PtrRoutingData pRoute);
  void _updateRoute();
  void _changeVariantIndex();
  void _reverseRoute();
  void _syncTiles();
  void _onNewProgress(const ProgressArray &array);

private:
  bool _setGenerator(PtrGenerator newG);
  void _setState(STATE state);
  void _setAreaData(PtrAreaData data);
  static bool _calculating(STATE state);
  static bool _editing(STATE state);
  static bool _idle(STATE state);
  void _updateFlightpathSegments();
  void _onAltitudeChanged();

  // Hirarcical stuff.
  int _sequenceNumber;
  bool _followTerrain;

  // State.
  STATE _state;

  // Facts
  QMap<QString, FactMetaData *> _metaDataMap;
  SettingsFact _altitude;
  SettingsFact _variantIndex;
  QStringList _variantNames;

  // Area data
  PtrAreaData _pAreaData;
  PtrAreaData _pEditorData;
  PtrAreaData _pCurrentData;
  bool _holdProgress;

  // Generators
  QList<PtrGenerator> _generatorList;
  PtrGenerator _pGenerator;

  // Routing.
  QVector<Variant> _variantVector;
  Variant _route;
  PtrWorker _pWorker;
};
