/**
 * 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 com.artenum.cassandra.pipeline.PipeLineManager;

import vtk.vtkActor;
import vtk.vtkOBJReader;
import vtk.vtkPolyDataMapper;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

public class ImportFromOBJ implements ActionListener {
    private PipeLineManager pipelineManager;
    private Frame owner;
    private vtkOBJReader reader;

    public ImportFromOBJ(PipeLineManager pipelineManager, Frame owner) {
        this.pipelineManager = pipelineManager;
        this.owner = owner;
        reader = new vtkOBJReader();
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".obj");
                }

                public String getDescription() {
                    return "OBJ files";
                }
            });
        if (chooser.showOpenDialog(owner) == JFileChooser.APPROVE_OPTION) {
            String file = chooser.getSelectedFile().getAbsolutePath();
            try {
                reader.SetFileName(file);
                reader.Update();
                pipelineManager.addDataSet(reader.GetOutput(), chooser.getSelectedFile().getName());
                vtkPolyDataMapper mapper = new vtkPolyDataMapper();
                mapper.SetInput(reader.GetOutput());
                pipelineManager.addMapper(mapper, "");
                vtkActor actor = new vtkActor();
                actor.SetMapper(mapper);
                pipelineManager.addActor(actor, "");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(owner, "Unable to load: " + file);
            }
        }
    }
}
