/*
 ----------------------------------------------------------------------------
 "THE BEER-WARE LICENSE" (Revision 42):
 <daniel.kratzert@ac.uni-freiburg.de> wrote this file. As long as you retain
 this notice you can do whatever you want with this stuff. If we meet some day,
 and you think this stuff is worth it, you can buy me a beer in return.
 Daniel Kratzert
 ----------------------------------------------------------------------------
*/

#include "plotgraph.h"
#include <QtGui>


RenderPlot::RenderPlot(int cycles, QWidget *parent)
    : QWidget(parent)
{
  dataPointShape = Ellipse;
  setBackgroundRole(QPalette::Base);
  setAutoFillBackground(true);
  originshift = 27;
  pen.setCapStyle(Qt::RoundCap);
  pen.setStyle(Qt::SolidLine);
  pen.setWidth(2);
  pen.setBrush(Qt::black);
  pen.setJoinStyle(Qt::RoundJoin);
  sclinespen.setCapStyle(Qt::RoundCap);
  sclinespen.setStyle(Qt::DotLine);
  sclinespen.setWidth(1);
  sclinespen.setBrush(QColor(80, 80, 80, 50));
  datapoints.clear();
  mcycles = cycles;
  startcycles = cycles;
  pointcolor = QBrush(Qt::green); //! color of the plot points
}

void RenderPlot::clearPlot() {
  datapoints.clear();
  this->update();
  mcycles = startcycles;
}

QSize RenderPlot::minimumSizeHint() const
{
  return QSize(150, 130);
}

QSize RenderPlot::sizeHint() const
{
  return QSize(250, 130);
}


void RenderPlot::setPen(const QPen &pen)
{
  this->pen = pen;
  update();
}

void RenderPlot::setBrush(const QBrush &brush)
{
  this->brush = brush;
  update();
}

void RenderPlot::setCycle(int numcycle) {
  this->mcycles = numcycle;
}

void RenderPlot::addPoint(qreal percent, int cycle){
  //! Add a point to the list of points.
  mypoint p;
  p.x = cycle;
  p.y = percent;
  bool found = false;
  if (datapoints.size() > 0) {
    foreach (mypoint p, datapoints) {
      if (p.x == cycle) {
        found = true;
      }
    }
  }
  // make sure only unique data points go into list:
  if (found){
    return;
  } else {
    datapoints.append(p);
  }
  // extends the x axis if more cycles are coming
  if ((cycle-mcycles) == 1) {
    mcycles += 1;
  }
  this->update();
}


void RenderPlot::drawScale() {
  //! Draws the axis scales. The origin ist shefted by "origignshift".
  //! The scale ticks are in the distances distx and disty.
  QPainter painter(this);
  painter.setPen(pen);
  painter.setBrush(brush);
  painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
  QFont font;
  font.setPointSize(11);
  painter.setFont(font);
  // The X axis line:
  painter.save();
  painter.translate(originshift, height()-originshift);
  painter.drawLine(0, 0, width(), 0);
  painter.translate(width()-40-originshift, -27);
  // The X axis label:
  QTextDocument tdx;
  tdx.setHtml("<font style=font-size:11pt> cycle </font>");
  tdx.drawContents(&painter);
  painter.restore();

  // The Y axis line:
  painter.save();
  painter.translate(originshift, height()-originshift);
  painter.drawLine(0, 0, 0, -height());
  painter.translate(5, -height()+originshift);
  QTextDocument tdy;
  // The Y axis label:
  tdy.setHtml("<font style=font-size:11pt>% <i>wR</i><sub>2</sub></font>");
  tdy.drawContents(&painter);
  painter.restore();
  // need highest y value to get scale right:
  QList<qreal> ylist;
  foreach (mypoint p, datapoints) {
    ylist.append(p.y);
  }
  qSort(ylist.begin(), ylist.end());
  distx = width() / (mcycles+1);
  // 14 is an empirical number and defines extra space on the y scale:
  if (ylist.length() > 1) {
    disty = height() / ((14*ylist.last()));
  } else { // default scale:
    disty = height() / 10;
  }

  // draw X scales
  qreal cycle = 0;
  for (qreal x = 0; x <= width(); x += distx) {
    painter.save();
    font.setPointSize(10);
    painter.setFont(font);
    // translate to left bottom corner+originshift:
    painter.translate(x+originshift, height()-originshift);
    // draw scale:
    painter.drawLine(0, 0, 0, 5);
    // draw intersetioon lines:
    if (x > 0 ) {
      painter.setPen(sclinespen);
      painter.drawLine(0, 0, 0, -height());
      painter.setPen(pen);
    }
    painter.drawText(-4, 19, QString("%1").arg(cycle));
    painter.restore();
    cycle += 1;
  }

  // draw Y scales
  // percent and stepsize could be defined outside to make the plotting more versatile:
  int percent = 0;
  int stepsize = 10;
  for (qreal y = 0; y <= (height() - (height()/stepsize)); y += disty) {
    painter.save();
    // translate to left bottom corner+originshift:
    painter.translate(originshift, height()-y-originshift);
    // draw scale:
    font.setPointSize(10);
    painter.setFont(font);
    painter.drawLine(-5, 0, 0, 0);
    painter.drawText(-24, 4, QString("%1").arg(percent));
    // draw intersection lines:
    if (y > 0) {
      painter.setPen(sclinespen);
      painter.drawLine(width(), 0, 0, 0);
      painter.setPen(pen);
    }
    painter.restore();
    percent += stepsize;
  }
}

void RenderPlot::drawPoints(const QList<mypoint> points, int pointsize) {
  //! Draws pre-defined points on the graph relative to the originshift.
  QPainter painter(this);
  QFont font;
  font.setPointSize(10);
  painter.setFont(font);
  painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  painter.setBrush(pointcolor);
  painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
  qreal x = 0;
  qreal y = 0;
  foreach (mypoint p, points) {
    painter.save();
    x = p.x*distx;
    y = -p.y*disty*10; // factor 10 could be defined outside to make plotting more versatile
    painter.translate(originshift, height()-originshift);
    // translate from 0, 0 of plot coordinate system,
    // therefore p.x*..., -p.y*...:
    painter.translate(x, y);
    // draw the y value as text:
    painter.drawText(-23, -8, QString("%1").arg(p.y*100, 10, 'f', 2));
    painter.drawEllipse(QPointF(0, 0), pointsize, pointsize);
    painter.restore();
  }
  painter.setPen(palette().dark().color());
  painter.setBrush(Qt::NoBrush);
  painter.drawRect(QRect(0, 0, width() - 1, height() - 1));
}

void RenderPlot::drawLines(const QList<mypoint> points) {
  //! Draws lines between data points.
  if (points.size() < 2) return;
  QPainter painter(this);
  painter.setPen(QPen(Qt::darkGray, 1, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin));
  painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
  qreal lastx = 0.0;
  qreal lasty = 0.0;
  qreal x = 0;
  qreal y = 0;
  foreach (mypoint p, points) {
    x = p.x*distx;
    y = -p.y*disty*10;
    painter.save();
    painter.translate(originshift, height()-originshift);
    if (x > distx) { //
      painter.drawLine(int(lastx), int(lasty), int(x), int(y));
    }
    lastx=x;
    lasty=y;
    painter.restore();
  }
  printf("\n");
}

void RenderPlot::paintEvent(QPaintEvent *)
//! This runs every time the widget changes.
{
  drawScale();
  drawLines(datapoints);
  drawPoints(datapoints, 3);
}


