package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JTable;

class CSVFileSaveListener implements ActionListener {
    private StartApplet applet;
    private int table_number;

    public CSVFileSaveListener(StartApplet applet, int table_number) {
        this.applet = applet;
        this.table_number = table_number;
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(applet);
        if ( returnVal == JFileChooser.APPROVE_OPTION ) {
            String filepath = fc.getSelectedFile().getPath();
            try {
                FileWriter writer = new FileWriter(filepath + ".csv");
                writer.write("No.,Actual value,Forecast,Error");
                writer.append('\n');

                JTable table = new JTable();
                switch ( table_number ) {
                    case 1:
                        table = applet.data_AR_Table;
                        break;
                    case 2:
                        table = applet.data_ABS_Table;
                        break;
                    case 3:
                        table = applet.test_data_AR_Table;
                        break;
                    case 4:
                        table = applet.test_data_ABS_Table;
                        break;
                }

                int data_Count = table.getRowCount();
                for ( int i = 0; i < data_Count; i++ ) {
                    String string1 = String.valueOf( table.getValueAt(i, 0) );
                    String string2 = String.valueOf( table.getValueAt(i, 1) );
                    String string3 = String.valueOf( table.getValueAt(i, 2) );
                    String string4 = String.valueOf( table.getValueAt(i, 3) );
                    writer.write( ( (string1 == null ? "null" != null : !string1.equals("null")) ? string1 : "" ) + "," +
                        ( (string2 == null ? "null" != null : !string2.equals("null")) ? string2 : "" ) + "," +
                        ( (string3 == null ? "null" != null : !string3.equals("null")) ? string3 : "" ) + "," +
                        ( (string4 == null ? "null" != null : !string4.equals("null")) ? string4 : "" ) );
                    writer.append('\n');
                }
                writer.close();
            }
            catch (IOException ex) {
                Logger.getLogger(CSVFileSaveListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}