#include "qvtkwidgetrendu3d.h"

#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QTimer>
#include <vtkProperty.h>

#include <iostream>
using namespace std;

QVTKWidgetRendu3d::QVTKWidgetRendu3d() : QVTKWidget()
{
    resize(512,512);

    nb_points = 0;

    QTimer *timerUpdatePolydata = new QTimer(this);
    connect(timerUpdatePolydata, SIGNAL(timeout()), this, SLOT(updatePolydata()));
    timerUpdatePolydata->start(200);

    QTimer *timerPeriodicRender = new QTimer(this);
    connect(timerPeriodicRender, SIGNAL(timeout()), this, SLOT(periodicRender()));
    timerPeriodicRender->start(100);

    // Setup points
    points = vtkSmartPointer<vtkPoints>::New();

     // Setup the colors array
    colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
    colors->SetNumberOfComponents(3);
    colors->SetName("Colors");

    // create a vertex
    vertex = vtkSmartPointer<vtkVertex>::New();

    // list of all the vertices
    vertices= vtkSmartPointer<vtkCellArray>::New();

    // Create a polydata object and add everything to it
    polydata = vtkSmartPointer<vtkPolyData>::New();
    polydata->SetPoints(points);
    polydata->SetVerts(vertices);
    polydata->GetPointData()->SetScalars(colors);

    mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    mapper->SetInputData(polydata);

    actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mapper);
    actor->GetProperty()->SetPointSize(5);

    // Setup window
    renderWindow = vtkSmartPointer<vtkRenderWindow>::New();

    // Setup renderer
    renderer = vtkSmartPointer<vtkRenderer>::New();
    renderWindow->AddRenderer(renderer);

    renderer->AddActor(actor);
    renderer->ResetCamera();
    this->SetRenderWindow(renderWindow);

    this->show();
}

void QVTKWidgetRendu3d::updatePolydata(void)
{
    nb_points++;
    if(nb_points<50)
    {
        points->Initialize();
        vertices->Initialize();
        colors->Initialize();

        for(quint8 i=0;i<nb_points;i++)
        {
            points->InsertNextPoint(i*0.01, 0.0, 0.0);
            vertex->GetPointIds()->SetId(0,i);
            vertices->InsertNextCell(vertex);
            /* the first point is red, others are blue */
            if(i==0)
                colors->InsertNextTuple3(255,0,0);
            else
                colors->InsertNextTuple3(0,0,255);
        }
        polydata->Modified();
    }
}

void QVTKWidgetRendu3d::periodicRender()
{
    renderWindow->Render();
}

