import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;

/**
 * Little pebl-test clone main windows <br>
 *                                     <br>
 * Elements for selecting test.        
 * User's input is collected from here 
 * like subjectNumber and when user is 
 * ready the test-classes are called to
 * be done from here.				   
 *                                     
 * @author Toni                        
 */

public class PeblTest extends JPanel
                      implements ListSelectionListener {
    private JList list;
    private DefaultListModel listModel;
 
    private static final String runTestString = "Run the test";
    private JTextField subjectNumber; 
    JButton runTestButton;
    
    int chosenTestIndex = 0;
    
    /**
    * Pebl test layout and basic stuff for starters.. 
	* Draw the panels like chosable tests which can be
	* added in here also if more needed.			   
	* Also panels like subject number and pebl-image  
	* are defined here to be printed.				   
    */
    public PeblTest() {
        super(new BorderLayout());
 
        listModel = new DefaultListModel();
        listModel.addElement("fourchoice");
        listModel.addElement("rotation");
        listModel.addElement("vsearch");
 
        //Create the list and put it in a scroll pane.
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        list.setVisibleRowCount(3);
        JScrollPane listScrollPane = new JScrollPane(list);

        runTestButton = new JButton(runTestString);
        RunTestListener runTestListener = new RunTestListener(runTestButton);
        runTestButton.setActionCommand(runTestString);
        runTestButton.addActionListener(runTestListener);
        runTestButton.setEnabled(false);
        
        subjectNumber = new JTextField(3);
        subjectNumber.addActionListener(runTestListener);
        subjectNumber.getDocument().addDocumentListener(runTestListener);
        String name = listModel.getElementAt(list.getSelectedIndex()).toString();
 
        JLabel subjectText  = new JLabel("Your subject number:");
        JLabel pickTestText = new JLabel("Pick pebl-test");
        ImageIcon icon = createImageIcon("pebl.gif", "Pebl-monster");
        JLabel iconLabel = new JLabel(icon);
        
        //Create a panel that uses BoxLayout.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane,BoxLayout.LINE_AXIS));
        
        buttonPane.add(subjectText);
        buttonPane.add(subjectNumber);
        
        buttonPane.add(Box.createHorizontalStrut(5));
        buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
        buttonPane.add(Box.createHorizontalStrut(5));
        
        buttonPane.add(runTestButton);
        buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
 
        add(pickTestText, BorderLayout.NORTH);
        add(listScrollPane, BorderLayout.CENTER);
        add(iconLabel, BorderLayout.EAST);
        add(buttonPane, BorderLayout.PAGE_END);
    }
 
    
	/**
	* This function is to create the logo image or     
	* can be used to create other imagelogo if neccessary	
    * @return an ImageIcon, or null if the path was    
	* invalid.										   
	* @see ImageIcon								   
    */
    protected static ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = PeblTest.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
     
	/**
	* This listener is shared by the text field and    
	* the runTestButton. We have to test that values   
	* are valid also.								   
	* If new test must be make selectable it's done    
	* here in the actionPerformed() -function.         
    */
    class RunTestListener implements ActionListener, DocumentListener {
        private boolean alreadyEnabled = false;
        private JButton button;
 
        public RunTestListener(JButton button) {
            this.button = button;
        }
 
        //Required by ActionListener.
        //Go to the tests..
        public void actionPerformed(ActionEvent e) {
            
            // Go with the selected tester
            if (listModel.getElementAt(list.getSelectedIndex()).equals("vsearch")) {
				// And see if user is ready to rock!
				TestInterface test = new vsearch();    
                vsearch.runTest(subjectNumber.getText());
			}
			if (listModel.getElementAt(list.getSelectedIndex()).equals("rotation")) {
				// And see if user is ready to rock!
				rotation test = new rotation();    
                test.runTest(subjectNumber.getText());
			}
			if (listModel.getElementAt(list.getSelectedIndex()).equals("fourchoice")) {
				// And see if user is ready to rock!
				fourchoice test = new fourchoice();    
                test.runTest(subjectNumber.getText());
			}
            
        }
 
        //This method tests for string equality. 
        protected boolean alreadyInList(String name) {
            return listModel.contains(name);
        }
 
        //Required by DocumentListener.
        public void insertUpdate(DocumentEvent e) {
            enableButton();
        }
 
        //Required by DocumentListener.
        public void removeUpdate(DocumentEvent e) {
            handleEmptyTextField(e);
        }
 
        //Required by DocumentListener.
        public void changedUpdate(DocumentEvent e) {
            if (!handleEmptyTextField(e) && chosenTestIndex > -1) {
                enableButton();
            }
        }
 
        private void enableButton() {
            if (!alreadyEnabled) {
                button.setEnabled(true);
            }
        }
 
        private boolean handleEmptyTextField(DocumentEvent e) {
            if (e.getDocument().getLength() <= 0) {
                button.setEnabled(false);
                alreadyEnabled = false;
                return true;
            }
            return false;
        }
    }
 
    //This method is required by ListSelectionListener and takes care of the selected test number.
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {
                chosenTestIndex = list.getSelectedIndex();
        }
    }
 
    /**
    * Create the GUI and show it.  For thread safety,  
    * this method should be invoked from the           
    * event-dispatching thread.                        
    */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Little Pebl Clone v1.0");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        JComponent newContentPane = new PeblTest();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
 
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
	
	/**
	* The main function of the class. This is called to 
	* drive this machine and takes care to call the     
    * function createAndShowGUI which starts the whole  
	* process..                                         
	*/
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
} // End of class pebl
