#pragma once

#include <QObject>
#include "QGCMapPolygon.h"
#include "QmlObjectListModel.h"

#include "WimaArea.h"
#include "WimaMeasurementArea.h"
#include "WimaServiceArea.h"
#include "WimaCorridor.h"
#include "WimaDataContainer.h"
#include "WimaMeasurementAreaData.h"
#include "WimaCorridorData.h"
#include "WimaServiceAreaData.h"

#include "PlanMasterController.h"
#include "MissionController.h"
#include "SurveyComplexItem.h"
#include "SimpleMissionItem.h"
#include "MissionSettingsItem.h"
#include "JsonHelper.h"
#include "QGCApplication.h"
#include "SettingsFact.h"


class WimaController : public QObject
{
    Q_OBJECT

    enum FileType {WimaFile, PlanFile};

public:
    WimaController(QObject *parent = nullptr);


    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(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(WimaDataContainer*       dataContainer           READ dataContainer          WRITE setDataContainer          NOTIFY dataContainerChanged)
    Q_PROPERTY(QmlObjectListModel*      missionItems            READ missionItems                                           NOTIFY missionItemsChanged)
    Q_PROPERTY(QmlObjectListModel*      currentMissionItems     READ currentMissionItems                                    NOTIFY currentMissionItemsChanged)
    Q_PROPERTY(QVariantList             waypointPath            READ waypointPath                                           NOTIFY waypointPathChanged)
    Q_PROPERTY(QVariantList             currentWaypointPath     READ currentWaypointPath                                    NOTIFY currentWaypointPathChanged)
    Q_PROPERTY(Fact*                    enableWimaController    READ enableWimaController                                   CONSTANT)
    Q_PROPERTY(Fact*                    overlapWaypoints        READ overlapWaypoints                                       CONSTANT)
    Q_PROPERTY(Fact*                    maxWaypointsPerPhase    READ maxWaypointsPerPhase                                   CONSTANT)
    Q_PROPERTY(Fact*                    startWaypointIndex      READ startWaypointIndex                                     CONSTANT)
    Q_PROPERTY(Fact*                    showAllMissionItems     READ showAllMissionItems                                    CONSTANT)
    Q_PROPERTY(Fact*                    showCurrentMissionItems READ showCurrentMissionItems                                CONSTANT)



    // Property accessors
    PlanMasterController*       masterController       (void)          { return _masterController; }
    MissionController*          missionController      (void)          { return _missionController; }
    QmlObjectListModel*         visualItems            (void);
    QString                     currentFile            (void) const    { return _currentFile; }
    QStringList                 loadNameFilters        (void) const;
    QStringList                 saveNameFilters        (void) const;
    QString                     fileExtension          (void) const    { return wimaFileExtension; }
    QGCMapPolygon               joinedArea             (void) const;
    WimaDataContainer*          dataContainer          (void);
    QmlObjectListModel*         missionItems           (void);
    QmlObjectListModel*         currentMissionItems    (void);
    QVariantList                waypointPath           (void);
    QVariantList                currentWaypointPath    (void);
    Fact*                       enableWimaController   (void);
    Fact*                       overlapWaypoints       (void);
    Fact*                       maxWaypointsPerPhase   (void);
    Fact*                       startWaypointIndex     (void);
    Fact*                       showAllMissionItems     (void);
    Fact*                       showCurrentMissionItems     (void);


    // Property setters
    void setMasterController        (PlanMasterController* masterController);
    void setMissionController       (MissionController* missionController);
    void setDataContainer           (WimaDataContainer* container);

    // Member Methodes
    Q_INVOKABLE void nextPhase();
    Q_INVOKABLE void previousPhase();
    Q_INVOKABLE void resetPhase();
    Q_INVOKABLE void uploadToVehicle();    
    Q_INVOKABLE void removeFromVehicle();
    Q_INVOKABLE void startMission();
    Q_INVOKABLE void abortMission();
    Q_INVOKABLE void pauseMission();
    Q_INVOKABLE void resumeMission();

    Q_INVOKABLE void saveToCurrent  ();
    Q_INVOKABLE void saveToFile     (const QString& filename);
    Q_INVOKABLE bool loadFromCurrent();
    Q_INVOKABLE bool loadFromFile   (const QString& filename);


    // static Members
    static const char* wimaFileExtension;
    static const char* areaItemsName;
    static const char* missionItemsName;    
    static const char* settingsGroup;
    static const char* endWaypointIndexName;
    static const char* enableWimaControllerName;
    static const char* overlapWaypointsName;
    static const char* maxWaypointsPerPhaseName;
    static const char* startWaypointIndexName;
    static const char* showAllMissionItemsName;
    static const char* showCurrentMissionItemsName;

    // Member Methodes
    QJsonDocument saveToJson(FileType fileType);

    bool calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QList<QGeoCoordinate> &path);
    /// extracts the coordinates stored in missionItems (list of MissionItems) and stores them in coordinateList
    bool extractCoordinateList(QmlObjectListModel &missionItems, QList<QGeoCoordinate> &coordinateList);
    /// extracts the coordinates (between startIndex and endIndex) stored in missionItems (list of MissionItems) and stores them in coordinateList.
    bool extractCoordinateList(QmlObjectListModel &missionItems, QList<QGeoCoordinate> &coordinateList, int startIndex, int endIndex);
    /// extracts the coordinates stored in missionItems (list of MissionItems) and stores them in coordinateList
    bool extractCoordinateList(QmlObjectListModel &missionItems, QVariantList &coordinateList);
    /// extracts the coordinates (between startIndex and endIndex) stored in missionItems (list of MissionItems) and stores them in coordinateList.
    bool extractCoordinateList(QmlObjectListModel &missionItems, QVariantList &coordinateList, int startIndex, int endIndex);

signals:
    void masterControllerChanged        (void);
    void missionControllerChanged       (void);
    void visualItemsChanged             (void);
    void currentFileChanged             ();
    void dataContainerChanged           ();
    void readyForSaveSendChanged        (bool ready);
    void missionItemsChanged            (void);
    void currentMissionItemsChanged     (void);
    void waypointPathChanged            (void);
    void currentWaypointPathChanged     (void);

private slots:
    void fetchContainerData                 (bool valid);
    void calcNextPhase                      (void);
    void updateWaypointPath                 (void);
    void updateCurrentPath                  (void);
    void updateNextWaypoint                 (void);
    void recalcCurrentPhase                 (void);


private:
    PlanMasterController   *_masterController;
    MissionController      *_missionController;
    QString                 _currentFile; // file for saveing
    WimaDataContainer      *_container; // container for data exchange with WimaController
    QmlObjectListModel      _visualItems; // contains all visible areas
    WimaJoinedAreaData      _joinedArea; // joined area fromed by opArea, serArea, _corridor
    WimaMeasurementAreaData _measurementArea; // measurement area
    WimaServiceAreaData     _serviceArea; // area for supplying
    WimaCorridorData        _corridor; // corridor connecting opArea and serArea
    bool                    _localPlanDataValid;
    QmlObjectListModel      _missionItems; // all mission itmes (Mission Items) generaded by wimaPlaner, displayed in flightView
    QmlObjectListModel      _currentMissionItems; // contains the current mission items, which are a sub set of _missionItems,
                                                  // _currentMissionItems contains a number of mission items which can be worked off with a single battery chrage
    QVariantList            _waypointPath; // path connecting the items in _missionItems
    QVariantList            _currentWaypointPath; // path connecting the items in _currentMissionItems
    QList<int>              _startWaypointIndexList; // list containing the last start waypoint indices, used by previosPhase

    QGeoCoordinate          _takeoffLandPostion;


    QMap<QString, FactMetaData*> _metaDataMap;
    SettingsFact                 _enableWimaController; // enables or disables the wimaControler
    SettingsFact                 _overlapWaypoints; // determines the number of overlapping waypoints between two consecutive mission phases
    SettingsFact                 _maxWaypointsPerPhase; // determines the maximum number waypoints per phase
    SettingsFact                 _nestPhaseStartWaypointIndex; // index (displayed on the map, -1 to get index of item in _missionItems) of the mission item
                                                      // defining the first element of the next phase
    SettingsFact                 _showAllMissionItems; // bool value, Determines whether the mission items of the overall mission are displayed or not.
    SettingsFact                 _showCurrentMissionItems; // bool value, Determines whether the mission items of the current mission phase are displayed or not.

    int                          _endWaypointIndex; // indes of the mission item stored in _missionItems defining the last element
                                                    // (which is not part of the return path) of _currentMissionItem
    int                          _startWaypointIndex; // indes of the mission item stored in _missionItems defining the first element
                                                      // (which is not part of the arrival path) of _currentMissionItem
};
