#include "scope.h"

#include <QPainter>
#include <QString>

#include <iostream>
#include <stdio.h> 

using namespace std;

#define TICK 150   // time in ms for one sampling (LEN values)
#define LEN 100    // number of sampled values

#define DEF_SCALE 256 //divisor
#define DEF_SHIFT 0

#define LEFT 10
#define TOP 10
#define PIXPT_X 4
#define PIXPT_Y 1
#define WIDTH (PIXPT_X*LEN)
#define HEIGHT (PIXPT_Y*512)


Scope::Scope(QWidget *parent) {
  dataAquired=0;

  data=new int[LEN*sizeof(int)]; ;

  int i;
  for(i=0;i<LEN;i++)
    data[i]=0;

  scale=DEF_SCALE;
  shift=DEF_SHIFT;
        
  scaleSlider = new QSlider(Qt::Horizontal);
  scaleSlider->setRange(1, 256);
  scaleSlider->setValue(DEF_SCALE);
  connect(scaleSlider, SIGNAL(valueChanged(int)), this, SLOT(setScale(int)));
        
  shiftSlider = new QSlider(Qt::Horizontal);
  shiftSlider->setRange(-60000, +60000);
  shiftSlider->setValue(DEF_SHIFT);
  connect(shiftSlider, SIGNAL(valueChanged(int)), this, SLOT(setShift(int)));

  updateTimer = new QTimer(this);
  updateTimer->start(TICK);
  connect(updateTimer, SIGNAL(timeout()), this, SLOT(getData()));
        
  scaleSlider->setGeometry(QRect(50,250,400,10));
  scaleSlider->show();
  shiftSlider->setGeometry(QRect(50,300,800,10));
  shiftSlider->show();

//  getData();

}


Scope::~Scope() {
  delete [] data;
}


void Scope::paintEvent(QPaintEvent* event) {

  QPainter painter(this);

/*  if (head>-1)
    painter.drawText(10,20,QString::number(data[head]));*/

  if (dataAquired) {
    painter.drawLine(LEFT-1,TOP,LEFT-1,TOP+HEIGHT);             //verticals
    painter.drawLine(LEFT+WIDTH+1,TOP,LEFT+WIDTH+1,TOP+HEIGHT);

    painter.drawLine(LEFT-1,TOP,LEFT+WIDTH+1,TOP);              //horizontals
    painter.drawLine(LEFT-1,TOP+HEIGHT,LEFT+WIDTH+1,TOP+HEIGHT);
    painter.drawLine(LEFT-1,TOP+HEIGHT/2,LEFT+WIDTH+1,TOP+HEIGHT/2);

    int i;
  
    for(i=0;i<LEN;i++) {
      data[i] = (data[i] + shift)/scale;
    }

    for(i=0;i<LEN-1;i++) {
      painter.drawLine(PIXPT_X*i+LEFT,TOP+HEIGHT/2-PIXPT_Y*data[i],PIXPT_X*(i+1)+LEFT,TOP+HEIGHT/2-data[i+1]*PIXPT_Y);
    }
  }
}


void Scope::getData() {
  char c='m';
  uint8_t buffer[2*LEN];
  

  FILE *serial=fopen("/dev/ttyUSB0","r+");
  fwrite(&c,sizeof(char),1,serial); // poprosime o data
  fread(buffer,sizeof(uint8_t),2*LEN,serial); // a berem je

  int i;
  for(i=0;i<LEN;i++) {
    data[i]=buffer[2*i]*256+buffer[2*i+1];
    cout << 1*data[i] <<endl;
  }
  dataAquired=1;
//  head=LEN-1;


  update();
//  cout << "Screen updated."<<endl;
}


void Scope::setScale(int val) {
        scale=val;
}

void Scope::setShift(int val) {
        shift=val;
}