#ifndef ADSPLOTWIDGET_H_
#define ADSPLOTWIDGET_H_

#include <QGraphicsView>

#include <QPointF>
#include <QVector>

#include <QColor>

class QGraphicsView;

class AdsPlotSamples
{
public:
  AdsPlotSamples():
      init(true)
  {
  }

  void clear()
  {
    values.clear();
    init=true;
  }

  void addSample(double x, double y)
  {
    addSample(QPointF(x, y));
  }

  void addSample(const QPointF& p)
  {
    values.push_back(p);
    double x=p.x();
    double y=p.y();

    if (init)
    {
      xmin=xmax=x;
      ymin=ymax=y;
      init=false;
      return;
    }
    if (x<xmin)
      xmin=x;
    else if (x>xmax)
      xmax=x;
    if (y<ymin)
      ymin=y;
    if (y>ymax)
      ymax=y;
  }

  double valueAt(double x) const { return valueAtOffset(x-xmin);}

  double valueAtOffset(double x) const;

  double x(int n) const { return values[n].x();}
  double y(int n) const { return values[n].y();}

  double x_min() const { return xmin;}
  double x_max() const { return xmax;}
  double y_min() const { return ymin;}
  double y_max() const { return ymax;}

  int samples() const { return values.size();}

private:
  bool init;
  double xmin, xmax, ymin, ymax;
  QVector<QPointF> values;
};

class AdsPlotWidgetSet;

class AdsPlotWidget: public QGraphicsView
{
  Q_OBJECT

public:
  explicit AdsPlotWidget(QWidget* parent=0);

  ~AdsPlotWidget();

  void setGroup(AdsPlotWidgetSet*);

  void clear();

  void serCursorPos(double x, double y);
  void syncPosX(double x, unsigned int crs);

  void setRangeX(double min, double max);

  void addSamples(const AdsPlotSamples& item, unsigned int scale, Qt::GlobalColor color);

  void recalculate();
  void update();

  void zoomIn();
  void zoomOut();

private:
  virtual void mouseMoveEvent(QMouseEvent *event);
  virtual void mousePressEvent(QMouseEvent *event);

  virtual void resizeEvent(QResizeEvent *event);

  class Private;
  Private& p_;

  class AdsPlotWidgetSet* wSet;

  friend class Private;
};

class AdsPlotWidgetSet: public QObject
{
  Q_OBJECT

public:
  explicit AdsPlotWidgetSet(QObject* parent=0);
  ~AdsPlotWidgetSet();

  void clear();
  void update();

  void addWidget(AdsPlotWidget* w);
  bool removeWidget(AdsPlotWidget* w);

  void setRangeX(double min, double max);

  AdsPlotWidget* plot(int n);

  void syncSelectCursor(unsigned int crs);
  unsigned int syncGetCursor() const;
  void syncPosX(AdsPlotWidget* from, double x, unsigned int crs);

  void zoomIn();
  void zoomOut();

signals:
  void cursorMoved(double x, unsigned int crs);

private slots:

private:

  class Private;
  Private& p_;

  friend class Private;
};

#endif /*ADSPLOTWIDGET_H_*/
