/**
 * Copyright (c) Artenum SARL 2004-2005
 * @author Julien Forest / Sebastien Jourdain
 *
 * All rights reserved. This software can
 * not be used or copy or diffused without
 * an explicit license of Artenum SARL, Paris-France
 */
package com.artenum.cassandra.plugin.defaults;

import vtk.vtkDataSet;
import vtk.vtkFloatArray;
import vtk.vtkIdList;
import vtk.vtkPoints;
import vtk.vtkUnstructuredGrid;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Sebastien
 */
public class Line3d {
    private ArrayList pointList;
    private vtkUnstructuredGrid grid;

    public Line3d() {
        pointList = new ArrayList();
        grid = null;
    }

    public void load(String filePath) throws IOException {
        FileReader fr = new FileReader(filePath);
        LineNumberReader lnr = new LineNumberReader(fr);
        String line = null;
        String[] split = null;
        double[] point = new double[3];
        int currentIndex;
        while ((line = lnr.readLine()) != null) {
            split = line.split(" ");
            currentIndex = 0;
            for (int i = 0; i < split.length; i++) {
                if (split[i].trim().length() > 0) {
                    point[currentIndex++] = Double.parseDouble(split[i]);
                }
            }

            addPoint(point[0], point[1], point[2]);
        }

        lnr.close();
    }

    public void addPoint(double x, double y, double z) {
        pointList.add(new double[] { x, y, z });
    }

    public void reset() {
        pointList.clear();
        grid = null;
    }

    private void buildVtkDataSet() {
        vtkIdList idList = null;
        int id = 0;
        grid = new vtkUnstructuredGrid();
        grid.Allocate(pointList.size() - 1, pointList.size());
        vtkPoints points = new vtkPoints();

        //
        vtkFloatArray pcoords = new vtkFloatArray();
        pcoords.SetNumberOfComponents(3);
        pcoords.SetNumberOfTuples(pointList.size());
        for (Iterator i = pointList.iterator(); i.hasNext();) {
            points.InsertPoint(id++, (double[]) i.next());
        }

        grid.SetPoints(points);

        // Set edge
        for (int i = 0; i < (id - 1); i++) {
            idList = new vtkIdList();
            idList.InsertNextId(i);
            idList.InsertNextId(i + 1);
            grid.InsertNextCell(3, idList);
        }

        grid.Update();
    }

    public vtkDataSet getDataSet() {
        if (grid == null) {
            buildVtkDataSet();
        }

        return grid;
    }
}
