#pragma once

#include <graph/plugins/plugin.h>
#include <graph/server/spec.h>
#include <QAction>
#include <QMenu>
#include <QMutex>
#include <limits>

namespace Graph::GUI {
class ChartWidget : public QWidget {
  Q_OBJECT

 public:
  ChartWidget(QWidget* parent = nullptr, const chart_spec_t& spec = chart_spec_t());
  ~ChartWidget();

  void addData(const char* seriesName, const point_t* points, unsigned long count);
  void clear();

 protected:
  QSize sizeHint() const override;
  void paintEvent(QPaintEvent* e) override;

 private:
  chart_spec_t spec;
  int decimateState = 0;
  QMutex mutex;

  struct series_t {
    double minX = std::numeric_limits<double>::max();
    double maxX = std::numeric_limits<double>::min();
    double minY = std::numeric_limits<double>::max();
    double maxY = std::numeric_limits<double>::min();
    std::list<point_t> points;
  };

  std::map<std::string, series_t> series;

  double scaleX, scaleY;
  int marginX = 40;
  int marginY = 40;
  QPointF pointToCoord(const point_t& point);
};

class ContextMenu : public QMenu {
  Q_OBJECT
 public:
  ContextMenu(QWidget* parent = nullptr, ChartWidget* chartWidget = nullptr);
  ~ContextMenu();

 private:
  QAction* remove;
  QAction* clear;
  QAction* edit;
};

} // namespace Graph::GUI
