/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#pragma once

#include "TransectStyleComplexItem.h"
#include "MissionItem.h"
#include "SettingsFact.h"
#include "QGCLoggingCategory.h"

Q_DECLARE_LOGGING_CATEGORY(SurveyComplexItemLog)

class SurveyComplexItem : public TransectStyleComplexItem
{
    Q_OBJECT

public:
    SurveyComplexItem(Vehicle* vehicle, bool flyView, QObject* parent);

    Q_PROPERTY(Fact*    gridAngle           READ gridAngle                                  CONSTANT)
    Q_PROPERTY(Fact*    gridEntryLocation   READ gridEntryLocation                          CONSTANT)

    Fact*   gridAngle           (void) { return &_gridAngleFact; }
    Fact*   gridEntryLocation   (void) { return &_gridEntryLocationFact; }

    // Overrides from ComplexMissionItem
    bool    load                (const QJsonObject& complexObject, int sequenceNumber, QString& errorString) final;
    QString mapVisualQML        (void) const final { return QStringLiteral("SurveyMapVisual.qml"); }

    // Overrides from TransectStyleComplexItem
    void    save                (QJsonArray&  planItems) final;
    bool    specifiesCoordinate (void) const final { return true; }
    void    appendMissionItems  (QList<MissionItem*>& items, QObject* missionItemParent) final;
    void    applyNewAltitude    (double newAltitude) final;

    // Overrides from VisualMissionionItem
    QString commandDescription  (void) const final { return tr("Survey"); }
    QString commandName         (void) const final { return tr("Survey"); }
    QString abbreviation        (void) const final { return tr("S"); }
    bool    readyForSave        (void) const final;

    // Must match json spec for GridEntryLocation
    enum EntryLocation {
        EntryLocationTopLeft,
        EntryLocationTopRight,
        EntryLocationBottomLeft,
        EntryLocationBottomRight,
    };

    static const char* jsonComplexItemTypeValue;
    static const char* settingsGroup;
    static const char* gridAngleName;
    static const char* gridEntryLocationName;

    static const char* jsonV3ComplexItemTypeValue;

signals:
    void refly90DegreesChanged(bool refly90Degrees);

private slots:
    // Overrides from TransectStyleComplexItem
    void _rebuildTransectsPhase1(void) final;
    void _rebuildTransectsPhase2(void) final;

private:
    enum CameraTriggerCode {
        CameraTriggerNone,
        CameraTriggerOn,
        CameraTriggerOff,
        CameraTriggerHoverAndCapture
    };

    QPointF _rotatePoint(const QPointF& point, const QPointF& origin, double angle);
    void _intersectLinesWithRect(const QList<QLineF>& lineList, const QRectF& boundRect, QList<QLineF>& resultLines);
    void _intersectLinesWithPolygon(const QList<QLineF>& lineList, const QPolygonF& polygon, QList<QLineF>& resultLines);
    void _adjustLineDirection(const QList<QLineF>& lineList, QList<QLineF>& resultLines);
    int _appendWaypointToMission(QList<MissionItem*>& items, int seqNum, QGeoCoordinate& coord, CameraTriggerCode cameraTrigger, QObject* missionItemParent);
    bool _nextTransectCoord(const QList<QGeoCoordinate>& transectPoints, int pointIndex, QGeoCoordinate& coord);
    bool _appendMissionItemsWorker(QList<MissionItem*>& items, QObject* missionItemParent, int& seqNum, bool hasRefly, bool buildRefly);
    void _optimizeTransectsForShortestDistance(const QGeoCoordinate& distanceCoord, QList<QList<QGeoCoordinate>>& transects);
    qreal _ccw(QPointF pt1, QPointF pt2, QPointF pt3);
    qreal _dp(QPointF pt1, QPointF pt2);
    void _swapPoints(QList<QPointF>& points, int index1, int index2);
    void _reverseTransectOrder(QList<QList<QGeoCoordinate>>& transects);
    void _reverseInternalTransectPoints(QList<QList<QGeoCoordinate>>& transects);
    void _adjustTransectsToEntryPointLocation(QList<QList<QGeoCoordinate>>& transects);
    bool _gridAngleIsNorthSouthTransects();
    double _clampGridAngle90(double gridAngle);
    void _buildAndAppendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent);
    void _appendLoadedMissionItems  (QList<MissionItem*>& items, QObject* missionItemParent);
    bool _imagesEverywhere(void) const;
    bool _triggerCamera(void) const;
    bool _hasTurnaround(void) const;
    double _turnaroundDistance(void) const;
    bool _hoverAndCaptureEnabled(void) const;
    bool _loadV3(const QJsonObject& complexObject, int sequenceNumber, QString& errorString);
    bool _loadV4(const QJsonObject& complexObject, int sequenceNumber, QString& errorString);
    void _rebuildTransectsPhase1Worker(bool refly);

    QMap<QString, FactMetaData*> _metaDataMap;

    SettingsFact    _gridAngleFact;
    SettingsFact    _gridEntryLocationFact;

    static const char* _jsonGridAngleKey;
    static const char* _jsonGridEntryLocationKey;

    static const char* _jsonV3GridObjectKey;
    static const char* _jsonV3GridAltitudeKey;
    static const char* _jsonV3GridAltitudeRelativeKey;
    static const char* _jsonV3GridAngleKey;
    static const char* _jsonV3GridSpacingKey;
    static const char* _jsonV3GridEntryLocationKey;
    static const char* _jsonV3TurnaroundDistKey;
    static const char* _jsonV3CameraTriggerDistanceKey;
    static const char* _jsonV3CameraTriggerInTurnaroundKey;
    static const char* _jsonV3HoverAndCaptureKey;
    static const char* _jsonV3GroundResolutionKey;
    static const char* _jsonV3FrontalOverlapKey;
    static const char* _jsonV3SideOverlapKey;
    static const char* _jsonV3CameraSensorWidthKey;
    static const char* _jsonV3CameraSensorHeightKey;
    static const char* _jsonV3CameraResolutionWidthKey;
    static const char* _jsonV3CameraResolutionHeightKey;
    static const char* _jsonV3CameraFocalLengthKey;
    static const char* _jsonV3CameraMinTriggerIntervalKey;
    static const char* _jsonV3ManualGridKey;
    static const char* _jsonV3CameraObjectKey;
    static const char* _jsonV3CameraNameKey;
    static const char* _jsonV3CameraOrientationLandscapeKey;
    static const char* _jsonV3FixedValueIsAltitudeKey;
    static const char* _jsonV3Refly90DegreesKey;


    static const int _hoverAndCaptureDelaySeconds = 4;
};
