#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);

    QTimer::singleShot(3000, this, SLOT(updateWidget()));

    // 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 PLY Writer */
    plyWriter = vtkSmartPointer<vtkPLYWriter>::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(10);

    // 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::updateWidget(void)
{
    points->Resize(4);
    points->SetPoint(0, 0.0, 0.0, 0.0);
    points->SetPoint(1, 1.0, 0.0, 0.0);
    points->SetPoint(2, 0.0, 1.0, 0.0);
    points->SetPoint(3, 0.0, 0.0, 1.0);

    vertices->Initialize();

    vertex->GetPointIds()->SetId(0,0);
    vertices->InsertNextCell(vertex);

    vertex->GetPointIds()->SetId(0,1);
    vertices->InsertNextCell(vertex);

    vertex->GetPointIds()->SetId(0,2);
    vertices->InsertNextCell(vertex);

    vertex->GetPointIds()->SetId(0,3);
    vertices->InsertNextCell(vertex);

    colors->Initialize();
    colors->InsertNextTuple3(255,0,0);
    colors->InsertNextTuple3(0,255,0);
    colors->InsertNextTuple3(0,0,255);
    colors->InsertNextTuple3(255,255,255);

    renderWindow->Render();

    QString plyFilePath = "output.ply";

    std::string filename = plyFilePath.toStdString();
    plyWriter->SetFileName(filename.c_str());

    plyWriter->SetInputData(polydata);
    plyWriter->SetColorModeToUniformPointColor();
    plyWriter->SetArrayName("Colors");
    plyWriter->SetFileTypeToASCII();
    plyWriter->Write();    
}

