import java.awt.FileDialog;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import Entidades_step.PontoCartesiano;

import jsdai.SMachining_schema.ECartesian_point;
import jsdai.SMachining_schema.SMachining_schema;
import jsdai.lang.A_double;
import jsdai.lang.SdaiException;
import jsdai.lang.SdaiModel;
import jsdai.lang.SdaiRepository;
import jsdai.lang.SdaiSession;

public class GeraCartesianPoint extends Coordinate_visual implements ActionListener {
	
	private static double X,Y,Z;
	private static String output = null; 
    private List<PontoCartesiano> listaDePontos = new ArrayList<PontoCartesiano>();  
        
	Help janela_ajuda = new Help();
		
	private void init1(){
		coordenada_adicionar.addActionListener(this);
		coordenada_salvar_localmente.addActionListener(this);
		coordenada_gerar_step.addActionListener(this);
		coordenada_abrir_localmente.addActionListener(this);
		coordenada_novo.addActionListener(this);
		coordenada_ok.addActionListener(this);
		coordenada_ajuda.addActionListener(this);
		coordenada_retornar.addActionListener(this);
	}	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		Object source = e.getSource();
		if(coordenada_gerar_step.equals(source)|coordenada_ok.equals(source)){
					
	        try {
				part21();
			} catch (SdaiException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}				
			listaDePontos.clear();
			coordenada_txt_step.setEditable(false);							
		}
		if(coordenada_adicionar.equals(source)){
			try{	     	
		    X = Double.parseDouble(coordenada_x.getText());
			Y = Double.parseDouble(coordenada_y.getText());
			Z = Double.parseDouble(coordenada_z.getText());
			
			PontoCartesiano ponto = new PontoCartesiano(X,Y,Z);
			listaDePontos.add(ponto);			
			JOptionPane.showMessageDialog(null, "Coordenada Adicionada!");
			}catch(NumberFormatException e1){
				JOptionPane.showMessageDialog(null, "Os argumentos devem ser números!");
			}
		}
		if(coordenada_salvar_localmente.equals(source)){
			savefile();			
		}
		if(coordenada_abrir_localmente.equals(source)){
			openfile();
			coordenada_txt_step.setEditable(false);
		}
		if(coordenada_novo.equals(source)){
			coordenada_txt_step.setEditable(true);
			coordenada_txt_step.setText("");
		}
		if(coordenada_ajuda.equals(source)){
			janela_ajuda.setVisible(true);
		}
		if(coordenada_retornar.equals(source)){
			this.setVisible(false);
		}
	}		
	private void part21() throws SdaiException{
				
		SdaiSession session = SdaiSession.openSession();
		session.startTransactionReadWriteAccess();
		SdaiRepository repository = session.createRepository("", null);
		repository.openRepository();
		SdaiModel model = repository.createSdaiModel("DemoSTEP_NC", SMachining_schema.class);
		model.startReadWriteAccess();
		coordenada_txt_step.setText(null);
		coordenada_txt_step.append("DATA;\n");
		
		for(PontoCartesiano ponto : listaDePontos){
			ECartesian_point cartesian_point = (ECartesian_point)model.createEntityInstance(ECartesian_point.class);
			cartesian_point.setName(null,"");
			A_double p = cartesian_point.createCoordinates(null);
			p.addByIndex(1, ponto.getX());
			p.addByIndex(2, ponto.getY());
			p.addByIndex(3, ponto.getZ());
			coordenada_txt_step.append(cartesian_point.toString()+"\n");
		}
		coordenada_txt_step.append("ENDSEC\n" +
				"END-ISO-10303-21;\n");
	/*
		FileDialog fd = new FileDialog(this, "salvar", FileDialog.SAVE);		
		fd.setVisible(true);
		String dir = fd.getDirectory();
		String file = fd.getFile();
		String filepath = dir + file + ".stp";
				
		try {
			ObjectOutputStream out = new ObjectOutputStream
			(new FileOutputStream(filepath,false));
			repository.exportClearTextEncoding(out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		*/		
		
		
	}	
	private void openfile() {	
		
		final JFileChooser chooseText = new JFileChooser();
		int returnVal = chooseText.showOpenDialog(GeraCartesianPoint.this);
		
		if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooseText.getSelectedFile();
            //This is where a real application would open the file.            
            if(true){
            getFileString(file);
            coordenada_txt_step.setText(output);                 	
            }
		}
   	} 	
	private void savefile(){
		String step_data;
		step_data = coordenada_txt_step.getText();
		JFileChooser savestp = new JFileChooser();
		if(savestp.showSaveDialog(GeraCartesianPoint.this) != JFileChooser.APPROVE_OPTION)
            return;        
         File arquivo = savestp.getSelectedFile();
         if(arquivo == null)
             return;
         FileWriter writer = null;
         try {
             writer = new FileWriter(arquivo);
             writer.write(step_data);
         }catch(IOException e){
        	 
         }
         finally {
             if(writer != null){
                try{
                    writer.close();
                } 
                catch (IOException x){
                       
             }
             }
          }
             
	}                	
	private static String getFileString(File file){
		try {
			FileReader reader = new FileReader(file);
			BufferedReader leitor = new BufferedReader(reader);

			Scanner s = new Scanner(leitor);
			String arquivo = "";

			while (s.hasNextLine()) {
				arquivo += s.nextLine();
				arquivo += "\n";				
			}			
			output = arquivo;
		}
		catch (Exception e) {			
		}
		return output;
	}
	
	public GeraCartesianPoint(){		
		init1();			
	}
	public List<PontoCartesiano> getListaDePontos() {
		return listaDePontos;
	}
	public void setListaDePontos(List<PontoCartesiano> listaDePontos) {
		this.listaDePontos = listaDePontos;
	}	
}
