// SortingDemoGUI2.java
// Demonstrates selection sort using file of short integers.
// Demonstrates use of a simple GUI to display the numbers.
//
// Replaces the array with a bigger array when necessary.
//
// Uses, in this directory:
//    SortingDemoExceptions.java
//    TextFileInput.java
//    TextFileOutput.java
//
// To compile this program in Java 1.4, type:
//    javac -source 1.4 SortingDemoGUI2.java
// (Compile it normally in Java 1.5 or later.)
//
// To run this program with assertions enabled, type:
//    java -ea SortingDemoGUI2
// (Otherwise, assertions are disabled.)


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * Sorts the numbers in a text file containing
 * short integers, one number per line, and
 * then displays, in text areas, both the original
 * list of numbers and the sorted version.
 *
 * @author Dorothy L. Nixon
 */
public class SortingDemoGUI2 extends JFrame
{
   final static int MAX_NUMBER_OF_NUMBERS = 40;

   private short[] numbers = new short[MAX_NUMBER_OF_NUMBERS];
   private int lengthFilled = 0;

   private JTextArea textAreaOriginal;
   private JTextArea textAreaSorted;
   private JTextField messageField;

   /**
    * Creates this window
    */
   public SortingDemoGUI2()
   {
      setSize(450, 300);
      setLocation(100, 100);
      setTitle("Sorts file of short integers");

      Container contentPane = getContentPane();

      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(1, 2));
      contentPane.add(panel, BorderLayout.CENTER);

      textAreaOriginal = new JTextArea();
      textAreaOriginal.setEditable(false);
      panel.add(new JScrollPane(textAreaOriginal));

      textAreaSorted = new JTextArea();
      textAreaSorted.setEditable(false);
      panel.add(new JScrollPane(textAreaSorted));

      messageField = new JTextField();
      messageField.setEditable(false);
      contentPane.add(messageField, BorderLayout.SOUTH);

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }  // constructor

   /**
    * Main method.
    *
    * @param args command-line arguments.
    *             One command-line argument is
    *             needed, for the input file.
    */
   public static void main(String[] args)
   {
      if ( args.length == 0 )
      {
         System.out.println("This program sorts short integers");
         System.out.println("from the file specified by a");
         System.out.println("command-line argument.");
         System.exit(0);
      } // if

      SortingDemoGUI2 window = new SortingDemoGUI2();
      final String inputFilename = args[0];

      window.open(inputFilename);
      window.sort();
      window.saveAs("sorted-" + inputFilename);
   }  // method main(String[])

   /**
    * Reads a list of numbers from the specified
    * text file, displays them to a text area,
    * and holds the list of numbers for further
    * use by this window.
    *
    * @param filename filename of input text file
    */
   private void open(String filename)
   {
      // Open file for reading:
      TextFileInput in = new TextFileInput(filename);

      // Read numbers into array:
      String line = in.readLine();   // read first line in file
      while ( line != null )
      {
         // If the array is already filled,
         // replace it with a bigger array:
         if ( lengthFilled >= numbers.length )
         {
            short[] temp = new short[numbers.length
                                     + lengthFilled + 2];
            for (int i = 0; i < numbers.length; i++)
               temp[i] = numbers[i];
            numbers = temp;
         }  // if

         // Put the most recently read number in the
         // array and continue reading from the file:
         numbers[lengthFilled] = Short.parseShort(line);
         lengthFilled++;
         line = in.readLine();       // read next line in file
      } // while

      // Close input file:
      in.close();

      // Display the numbers to the text area intended
      // for display of as-yet unsorted list of numbers:
      displayNumbers(textAreaOriginal);
   }  // method open

   /**
    * Sorts this window's list of numbers and
    * displays the sorted list to a text area.
    */
   private void sort()
   {
      SortingDemoExceptions.selectionSort(numbers, lengthFilled);
      displayNumbers(textAreaSorted);
   }  // method sortAndDisplay

   /**
    * Outputs this window's list of numbers to
    * the specified text file
    *
    * @param filename text file for output of
    *                 list of numbers
    */
   private void saveAs(String filename)
   {
      // Create file for output:
      TextFileOutput out = new TextFileOutput(filename);

      // Print numbers to output text file:
      for ( int i = 0; i < lengthFilled; i++ )
         out.println(numbers[i]);

      // Make sure the output finds its way to the file,
      // and close it:
      out.flush();
      out.close();

      // Print message indicating successful completion:
      messageField.setText("File " + filename
                                 + " has been created.");

   }  // method saveAs

   /**
    * Displays this window's list of numbers
    * to the specified text area.
    * 
    * @param textArea text area where numbers will be displayed.
    */
   private void displayNumbers(JTextArea textArea)
   {
      String lineBreak = System.getProperty("line.separator");
      for ( int i = 0; i < lengthFilled; i++ )
      {
         textArea.append(Double.toString(numbers[i]));
         textArea.append(lineBreak);
      } // for
   }  // method displayNumbers
}  // class SortingDemoGUI2