import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;


public class Parte21 extends Parte21_visual implements ActionListener{

	private static String output = null;
	
	public void init(){
		salvar_txt.addActionListener(this);
		abrir_txt.addActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if(salvar_txt.equals(source)){
			savefile();
		}
		if(abrir_txt.equals(source)){
			openfile();
		}		
	}
	private void openfile() {
		final JFileChooser chooseText = new JFileChooser();
		int returnVal = chooseText.showOpenDialog(Parte21.this);
		
		if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooseText.getSelectedFile();
            //This is where a real application would open the file.            
            if(true){
            getFileString(file);
            txt_parte21.setText(output);                 	
            }
		}
	}
	public 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 void savefile(){
		String step_data;
		step_data = txt_parte21.getText();
		JFileChooser savestp = new JFileChooser();
		if(savestp.showSaveDialog(Parte21.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){
                       
             }
             }
          }
             
	}                	
	
	public Parte21(){
		init();
	}

}
