#pragma once

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

#include "WimaArea.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 WimaMeasurementArea : public WimaArea {
  Q_OBJECT

  enum class STATE { IDLE, DEFERED, UPDATEING, RESTARTING, STOP };

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

  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 WimaPolygon
  QString mapVisualQML(void) const;
  QString editorQML(void) const;

  // 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;

  // Member Methodes
  void saveToJson(QJsonObject &json);
  bool loadFromJson(const QJsonObject &json, QString &errorString);

  // Static Variables
  static const char *settingsGroup;
  static const char *tileHeightName;
  static const char *tileWidthName;
  static const char *minTileAreaName;
  static const char *showTilesName;
  static const char *WimaMeasurementAreaName;

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.
  mutable QTimer _timer;
  using DataPtr = std::shared_ptr<TileData>;
  mutable STATE _state;
  mutable TileData _tileData;
  mutable QFutureWatcher<DataPtr> _watcher;
};
