package taberion;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.*;

public class THandleCSV extends JDialog {

    public void centerScreen() {
       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
       Dimension frameSize = this.getSize();
       if (frameSize.height > screenSize.height)
       {
         frameSize.height = screenSize.height;
       }
       if (frameSize.width > screenSize.width)
       {
         frameSize.width = screenSize.width;
       }
       this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    }


    public THandleCSV(Frame owner) {
      super(owner, "Load a CSV file");
      //Create a file chooser
      centerScreen();
      setModal(true);
      log.setMargin(new Insets(5,5,5,5));
      log.setEditable(false);
      log.setBackground(TConsts.startMinCol);
      JScrollPane logScrollPane = new JScrollPane(log);

      final JFileChooser fc = new JFileChooser("C:" + File.separatorChar);

      JButton openButton = new JButton("Choose the CSV-file..."); //, openIcon);
      openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          int returnVal = fc.showOpenDialog(THandleCSV.this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //this is where a real application would save the file.
            log.append("Loading from file: " + file.toString() + ".\n");
            fileName = file.toString();
          } else {
            log.append("Load command cancelled by user.\n");
          }
        }
      });

      //The button for cleaning
      JButton cleanButton = new JButton("Clean Output");
      cleanButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // Quit...
          log.selectAll();
          log.replaceSelection("");
        }
      });

      //The button to start everything
      JButton doitButton = new JButton("Load the CSV info from file.");
      doitButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // Create file and write the contents into it:
          if (fileName.equals("")) {
            log.append("File to save into is not specified.\n");
            return;
          }

      	  //System.out.println ("Filename : " + fileName);
          loadMatrixFromFile(fileName);
	        setVisible(false);
	        dispose();
        }
      });

      //For layout purposes, put the buttons in a separate panel
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(addCSVPanel());
      buttonPanel.add(cleanButton);


      //For layout purposes, put the buttons in a seperate panel
      JPanel goPanel = new JPanel();
      goPanel.add(openButton);
      goPanel.add(doitButton);

      //Add the buttons and the log to the frame
      Container contentPane = getContentPane();
      contentPane.add(buttonPanel, BorderLayout.NORTH);
      contentPane.add(logScrollPane, BorderLayout.CENTER);
      //contentPane.add(addCSVPanel(), BorderLayout.WEST);
      contentPane.add(goPanel, BorderLayout.SOUTH);

      pack();
      setVisible(true);
    }

    public THandleCSV(Frame owner, String[][] matrix) {
      super(owner, "Save a CSV file");
      centerScreen();
      //System.out.println("Got the matrix" + matrix);
      theMatrix = matrix;
      setModal(true);
      //Create a file chooser
      log.setMargin(new Insets(5,5,5,5));
      log.setEditable(false);
      log.setBackground(TConsts.startMinCol);
      JScrollPane logScrollPane = new JScrollPane(log);

      final JFileChooser fc = new JFileChooser("C:" + File.separatorChar);

      JButton openButton = new JButton("Choose the CSV-file..."); //, openIcon);
      openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          int returnVal = fc.showOpenDialog(THandleCSV.this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //this is where a real application would save the file.
            log.append("Saving to file: " + file.toString() + ".\n");
            fileName = file.toString();
          } else {
            log.append("Save command cancelled by user.\n");
          }
        }
      });

      //The button for cleaning
      JButton cleanButton = new JButton("Clean Output");
      cleanButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // Quit...
          log.selectAll();
          log.replaceSelection("");
        }
      });


      JButton doitButton = new JButton("Save the CSV info to file.");
      doitButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // Create file and write the contents into it:
          if (fileName.equals("")) {
            log.append("File to save into is not specified.\n");
            return;
          }

      	  //System.out.println ("Filename : " + fileName);
          saveMatrixToFile(fileName);
	        setVisible(false);
	        dispose();
        }
      });

      //For layout purposes, put the buttons in a separate panel
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(addCSVPanel());
      buttonPanel.add(cleanButton);

      //For layout purposes, put the buttons in a seperate panel
      JPanel goPanel = new JPanel();
      goPanel.add(openButton);
      goPanel.add(doitButton);

      //Add the buttons and the log to the frame
      Container contentPane = getContentPane();
      contentPane.add(buttonPanel, BorderLayout.NORTH);
      contentPane.add(logScrollPane, BorderLayout.CENTER);
      //contentPane.add(addCSVPanel(), BorderLayout.WEST);
      contentPane.add(goPanel, BorderLayout.SOUTH);

      pack();
      setVisible(true);
    }

    private JPanel addCSVPanel() {
      JPanel cvsPanel = new JPanel(new GridLayout(1,2));

      // Create the combo box
      cvsComboBox = new JComboBox(cvsStrings);
      cvsComboBox.setSelectedIndex(0);

      cvsPanel.add(new JLabel("CSV Separator:"));
      cvsPanel.add(cvsComboBox);

      return cvsPanel;
    }



    private void saveMatrixToFile(String filename) {
      int width = theMatrix.length;
      int height = theMatrix[0].length;
      String line;

      BufferedWriter f;
      try {
        f = new BufferedWriter(new FileWriter(fileName));
      }
      catch (Exception e) {
      	System.out.println ("Error while writing the file. lMMF");
      	return;
      }

      try {
        for (int j=0; j < height; j++) {
          line = "";
          for (int i=0; i < width-1;i++) {
            line += theMatrix[i][j] + cvsComboBox.getSelectedItem().toString();
        	}
        	// To avoid a separator at the end.
        	line += theMatrix[width-1][j];
        	log.append("Writing to file line " + j + ": " + line + "\n");
          f.write(line);
          f.newLine();
        }
        f.close();
      }
      catch (IOException e) {
        System.out.println("Error reading the file (lMFF)...");
      }

    }

    private int getLines(String filename) {
      int mSize = 0;
      String line;

      try {
        BufferedReader f = new BufferedReader(new FileReader(fileName));
        while ((line = f.readLine()) != null) {
        	mSize++;
        }
        f.close();
      }
      catch (Exception e) {
      	System.out.println ("Error while reading the file. lMMF");
      	return -1;
      }

      return mSize;
    }

    private void loadMatrixFromFile(String filename) {

      int mSize =  getLines(filename);

      if (mSize == -1) {
      	System.out.println ("Could not load file.");
      	return;
      }

      BufferedReader f;
      try {
        f = new BufferedReader(new FileReader(fileName));
      }
      catch (Exception e) {
      	System.out.println ("Error while reading the file (in loadMAtrixFromFile).");
      	return;
      }

      theMatrix = new String[mSize][];
      int row = 0;
      String line;
      String entries[];

      try {
        while ((line = f.readLine()) != null) {
          entries = line.split(cvsComboBox.getSelectedItem().toString());
          theMatrix[row] = entries; row++;
          log.append("Added entries to line " + row + " : ");
          for (int i=0;i < entries.length;i++) {
            log.append(entries[i] + "<>");
          }
          log.append("\n");
        }
        f.close();
      }
      catch (IOException e) { System.out.println("Error reading the file (lMFF)...");}
    }

    public String[][] getMatrix() {
      return theMatrix;
    }

    private String[] cvsStrings = { ";",":","|"};
    private final JTextArea log = new JTextArea(5,20);


    private JComboBox cvsComboBox;
    private String fileName = "";
    private String[][] theMatrix = null;

    private Object waitMutex = new Object();

}