#pragma once

#include <QFutureWatcher>
#include <QObject>
#include <QSharedPointer>
#include <QTimer>

#include "GeoArea.h"

#include "SettingsFact.h"

class TileData : public QObject {
public:
  QmlObjectListModel tiles;
  QVariantList tileCenterPoints;

  TileData();
  ~TileData();

  TileData &operator=(const TileData &other);
  bool operator==(const TileData &other) const;
  bool operator!=(const TileData &other) const;

  void clear();
  std::size_t size() const;
};

class MeasurementArea : public GeoArea {
  Q_OBJECT
  enum class STATE { IDLE, DEFERED, UPDATEING, RESTARTING, STOP };
  using DataPtr = QSharedPointer<TileData>;

public:
  MeasurementArea(QObject *parent = nullptr);
  MeasurementArea(const MeasurementArea &other, QObject *parent = nullptr);
  MeasurementArea &operator=(const MeasurementArea &other);
  ~MeasurementArea();

  Q_PROPERTY(Fact *tileHeight READ tileHeight CONSTANT)
  Q_PROPERTY(Fact *tileWidth READ tileWidth CONSTANT)
  Q_PROPERTY(Fact *minTileArea READ minTileArea CONSTANT)
  Q_PROPERTY(Fact *showTiles READ showTiles CONSTANT)
  Q_PROPERTY(QmlObjectListModel *tiles READ tiles NOTIFY tilesChanged)
  Q_PROPERTY(int maxTiles READ maxTiles NOTIFY maxTilesChanged)
  Q_PROPERTY(QVector<int> progress READ progressQml NOTIFY progressChanged)

  // Overrides from GeoArea
  QString mapVisualQML(void) const override;
  QString editorQML(void) const override;
  MeasurementArea *clone(QObject *parent = nullptr) const;
  bool saveToJson(QJsonObject &json) override;
  bool loadFromJson(const QJsonObject &json, QString &errorString) override;
  Q_INVOKABLE virtual bool isCorrect();

  // Property getters.
  Fact *tileHeight();
  Fact *tileWidth();
  Fact *minTileArea();
  Fact *showTiles();
  QmlObjectListModel *tiles();
  const QVector<int> &progress() const;
  QVector<int> progressQml() const;
  const QmlObjectListModel *tiles() const;
  const QVariantList &tileCenterPoints() const; // List of QGeoCoordinate
  const TileData &tileData() const;
  int maxTiles() const;
  bool ready() const;

  // Static Variables
  static const char *settingsGroup;
  static const char *name;

signals:
  void tilesChanged();
  void maxTilesChanged();
  void progressChanged();
  void progressAccepted();
  void progressNotAccepted();
  void readyChanged();

public slots:
  bool setProgress(const QVector<int> &p);

private slots:
  void doUpdate();
  void deferUpdate();
  void storeTiles();
  void disableUpdate();
  void enableUpdate();

private:
  // Member Methodes
  void init();
  void setState(STATE s);

  // Members
  QMap<QString, FactMetaData *> _metaDataMap;

  SettingsFact _tileHeight;
  SettingsFact _tileWidth;
  SettingsFact _minTileAreaPercent; // 0..100
  SettingsFact _showTiles;

  QVector<int> _progress;
  // Tile stuff.
  // Tile stuff.
  mutable QTimer _timer;
  mutable STATE _state;
  mutable TileData _tileData;
  mutable QFutureWatcher<DataPtr> _watcher;
};
