#pragma once

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

#include "GeoArea.h"

#include "ProgressArray.h"
#include "SettingsFact.h"

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

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)

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

  // Property getters.
  Fact *tileHeight();
  Fact *tileWidth();
  Fact *minTileArea();
  Fact *showTiles();
  QmlObjectListModel *tiles();
  const QmlObjectListModel *tiles() const;
  int maxTiles() const;
  bool ready() const;

  bool measurementCompleted() const;

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

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

public slots:
  void updateProgress(const ProgressArray &array);
  Q_INVOKABLE void randomProgress();
  Q_INVOKABLE void resetProgress();

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;

  // Tile stuff.
  bool _toManyTiles;
  TilePtr _tiles;
  std::map<QString /*id*/, int> _indexMap;
  QTimer _timer;
  STATE _state;
  QFutureWatcher<TilePtr> _watcher;
};
