#pragma once

#include "QmlObjectListModel.h"
#include <QObject>
#include <QScopedPointer>
#include <QSharedPointer>

#include "Geometry/WimaCorridor.h"
#include "Geometry/WimaCorridorData.h"
#include "Geometry/WimaJoinedArea.h"
#include "Geometry/WimaJoinedAreaData.h"
#include "Geometry/WimaMeasurementArea.h"
#include "Geometry/WimaMeasurementAreaData.h"
#include "Geometry/WimaServiceArea.h"
#include "Geometry/WimaServiceAreaData.h"
#include "WimaPlanData.h"

#include "Snake/NemoInterface.h"

#include "JsonHelper.h"

class MissionController;
class PlanMasterController;

namespace wima_planer_detail {
class StateMachine;
}

class WimaPlaner : public QObject {
  Q_OBJECT

  enum FileType { WimaFile, PlanFile };

public:
  WimaPlaner(QObject *parent = nullptr);
  ~WimaPlaner();
  template <class T> WimaPlaner(T t, QObject *parent = nullptr) = delete;
  template <class T> WimaPlaner(T t) = delete;

  Q_PROPERTY(PlanMasterController *masterController READ masterController WRITE
                 setMasterController NOTIFY masterControllerChanged)
  Q_PROPERTY(MissionController *missionController READ missionController WRITE
                 setMissionController NOTIFY missionControllerChanged)
  Q_PROPERTY(QmlObjectListModel *visualItems READ visualItems NOTIFY
                 visualItemsChanged)
  Q_PROPERTY(int currentPolygonIndex READ currentPolygonIndex WRITE
                 setCurrentPolygonIndex NOTIFY currentPolygonIndexChanged)
  Q_PROPERTY(QString currentFile READ currentFile NOTIFY currentFileChanged)
  Q_PROPERTY(QStringList loadNameFilters READ loadNameFilters CONSTANT)
  Q_PROPERTY(QStringList saveNameFilters READ saveNameFilters CONSTANT)
  Q_PROPERTY(QString fileExtension READ fileExtension CONSTANT)
  Q_PROPERTY(QGeoCoordinate joinedAreaCenter READ joinedAreaCenter CONSTANT)
  Q_PROPERTY(NemoInterface *nemoInterface READ nemoInterface CONSTANT)
  Q_PROPERTY(bool synchronized READ synchronized NOTIFY synchronizedChanged)
  Q_PROPERTY(bool needsUpdate READ needsUpdate NOTIFY needsUpdateChanged)
  Q_PROPERTY(bool readyForSynchronization READ readyForSynchronization NOTIFY
                 readyForSynchronizationChanged)
  Q_PROPERTY(bool progressLocked READ progressLocked WRITE setProgressLocked
                 NOTIFY progressLockedChanged)

  // Property accessors
  PlanMasterController *masterController(void);
  MissionController *missionController(void);
  QmlObjectListModel *visualItems(void);
  int currentPolygonIndex(void) const;
  QString currentFile(void) const;
  QStringList loadNameFilters(void) const;
  QStringList saveNameFilters(void) const;
  QString fileExtension(void) const;
  QGeoCoordinate joinedAreaCenter(void) const;
  NemoInterface *nemoInterface(void);
  bool synchronized();
  bool needsUpdate();
  bool readyForSynchronization();
  bool progressLocked();

  // Property setters
  void setMasterController(PlanMasterController *masterController);
  void setMissionController(MissionController *missionController);
  /// Sets the integer index pointing to the current polygon. Current polygon is
  /// set interactive.
  void setCurrentPolygonIndex(int index);
  void setProgressLocked(bool l);

  Q_INVOKABLE bool addMeasurementArea();
  /// Removes an area from _visualItems
  /// @param index Index of the area to be removed
  Q_INVOKABLE void removeArea(int index);
  Q_INVOKABLE bool addServiceArea();
  Q_INVOKABLE bool addCorridor();
  /// Remove all areas from WimaPlaner and all mission items from
  /// MissionController
  Q_INVOKABLE void removeAll();
  /// Recalculates vehicle corridor, flight path, etc.
  Q_INVOKABLE void update();
  /// Pushes the generated mission data to the wimaController.
  Q_INVOKABLE void synchronize();
  Q_INVOKABLE void saveToCurrent();
  Q_INVOKABLE void saveToFile(const QString &filename);
  Q_INVOKABLE bool loadFromCurrent();
  Q_INVOKABLE bool loadFromFile(const QString &filename);
  Q_INVOKABLE void resetAllInteractive(void);
  Q_INVOKABLE void setInteractive(void);

  QJsonDocument saveToJson(FileType fileType);
  // static Members
  static const char *wimaFileExtension;
  static const char *areaItemsName;
  static const char *missionItemsName;

signals:
  void masterControllerChanged(void);
  void missionControllerChanged(void);
  void visualItemsChanged(void);
  void currentPolygonIndexChanged(int index);
  void currentFileChanged();
  void wimaBridgeChanged();
  void synchronizedChanged(void);
  void needsUpdateChanged(void);
  void readyForSynchronizationChanged(void);
  void progressLockedChanged();

private slots:
  void updatePolygonInteractivity(int index);
  void _update();
  void CSDestroyedHandler();
  void CSMissionItemReadyHandler();
  void CSCalculatingChangedHandler();
  void mAreaPathChangedHandler();
  void mAreaTilesChangedHandler();
  void mAreaProgressChangedHandler();
  void mAreaProgressAcceptedHandler();
  void mAreaReadyChangedHandler();
  void sAreaPathChangedHandler();
  void corridorPathChangedHandler();
  void depotChangedHandler();
  void missionControllerVisualItemsChangedHandler();
  void missionControllerWaypointPathChangedHandler();
  void missionControllerNewItemsFromVehicleHandler();
  void missionControllerMissionItemCountChangedHandler();
  void nemoInterfaceProgressChangedHandler();

#ifndef NDEBUG
  void autoLoadMission(void);
#endif

private:
signals:
  void joinedAreaValidChanged();
  void stateChanged();

private:
  // Member Functions
  bool toPlanData(WimaPlanData &planData);
  bool shortestPath(const QGeoCoordinate &start,
                    const QGeoCoordinate &destination,
                    QVector<QGeoCoordinate> &path);
  void setSynchronized(bool s);
  void enableAreaMonitoring();
  void disableAreaMonitoring();
  void enableMissionControllerMonitoring();
  void disableMissionControllerMonitoring();
  bool areasMonitored();
  bool missionControllerMonitored();

  // Member Variables
  PlanMasterController *_masterController;
  MissionController *_missionController;
  int _currentAreaIndex;
  QString _currentFile;

  bool _joinedAreaValid;
  WimaMeasurementArea _measurementArea;
  bool _copyMAreaToSurvey;
  WimaServiceArea _serviceArea;
  bool _copySAreaToSurvey;
  WimaCorridor _corridor;
  bool _corridorChanged;
  // contains all visible areas
  QmlObjectListModel _visualItems;
  // joined area fromed by _measurementArea, _serviceArea, _corridor
  WimaJoinedArea _joinedArea;
  // path from takeoff to first measurement point
  unsigned long _arrivalPathLength;
  // path from last measurement point to land
  unsigned long _returnPathLength;

  CircularSurvey *_survey;
  bool _surveyChanged;
  // sync stuff
  bool _synchronized; // true if planData is synchronized with
                      // wimaController

#ifndef NDEBUG
  QTimer _autoLoadTimer; // timer to auto load mission after some time, prevents
                         // seg. faults
#endif

  NemoInterface _nemoInterface;

  // State
  QScopedPointer<wima_planer_detail::StateMachine> _stateMachine;
  bool _areasMonitored;
  bool _missionControllerMonitored;
  bool _progressLocked;
};
