#pragma once

#include <QObject>

#include "QGCMapPolygon.h"

class GeoArea : public QGCMapPolygon {
  Q_OBJECT
public:
  GeoArea(QObject *parent = nullptr);
  GeoArea(const GeoArea &other, QObject *parent = nullptr);
  GeoArea &operator=(const GeoArea &other);

  Q_PROPERTY(QString mapVisualQML READ mapVisualQML CONSTANT)
  Q_PROPERTY(QString editorQML READ editorQML CONSTANT)
  Q_PROPERTY(QString errorString READ errorString NOTIFY errorStringChanged)

  virtual QString mapVisualQML(void) const = 0;
  virtual QString editorQML(void) const = 0;

  virtual bool saveToJson(QJsonObject &jsonObject);
  virtual bool loadFromJson(const QJsonObject &jsonObject,
                            QString &errorString);

  virtual GeoArea *clone(QObject *parent = nullptr) const = 0;

  Q_INVOKABLE virtual bool isCorrect();
  Q_INVOKABLE QString errorString() const;

  //!
  //! \brief covers Checks if GeoArea covers c.
  //! \param c
  //! \return  Returns true if c is inside, or on the border of GeoArea, false
  //! either.
  //!
  Q_INVOKABLE bool covers(const QGeoCoordinate &c);

  // static Members
  static const char *nameString;
  static const char *areaTypeKey;
  static const char *settingsGroup;

signals:
  void errorStringChanged();

protected:
  void setErrorString(const QString &str);
  void setErrorString(const std::string &str);

private:
  void init();

  QString _errorString;
};

// Example usage:
// QmlObjecListModel list;
// .... add areas ....
// auto area = getGeoArea<MeasurementArea *>(list); // returns the first
// MeasurementArea or nullptr
//! \example
//!
//! QmlObjecListModel list;
//! // .... add areas ....
//! auto area = getGeoArea<MeasurementArea *>(list); // returns the first
//! MeasurementArea or nullptr
template <class AreaPtr, class QObjectList>
inline AreaPtr getGeoArea(QObjectList &list) {
  static_assert(std::is_pointer<AreaPtr>::value,
                "AreaPtr must be a pointer type.");
  for (int i = 0; i < list.count(); ++i) {
    auto obj = list[i];
    auto area = qobject_cast<AreaPtr>(obj);
    if (area != nullptr) {
      return area;
    }
  }
  return nullptr;
}

//! \example
//!
//! QmlObjecListModel list;
//! // .... add areas ....
//! auto areaArray = getGeoAreaArray<MeasurementArea *>(list); // returns a
//! QList<MeasurementArea*>
//! // containing all MeasurementArea's inside list
template <class AreaPtr, template <class> class Container = QList,
          class QObjectList>
inline Container<AreaPtr> getGeoAreaList(QObjectList &list) {
  static_assert(std::is_pointer<AreaPtr>::value,
                "AreaPtr must be a pointer type.");
  Container<AreaPtr> out;
  for (int i = 0; i < list.count(); ++i) {
    auto obj = list[i];
    auto area = qobject_cast<AreaPtr>(obj);
    if (area != nullptr) {
      out.append(area);
    }
  }
  return out;
}

bool copyAreaList(const QmlObjectListModel &from, QmlObjectListModel &to,
                  QObject *parent);
