/* Program: Questionnaire
 * Author: Rytis Umbrasas
 * School: Vilnius Lyceum
 * IDE: NetBeans 4.1
 */

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class QuestionEditor extends application{
    
    public Browser FileChooser;
    
    private boolean isNew;
    private int QuestionId;
    private String multimedia;
    
    private JComboBox TypeCombo;
    private JPanel PanelChoices;
    private JLabel LabelQuestion, LabelType, LabelLocation, LabelImage;
    private JLabel[] LabelChoices;
    private JTextField FieldQuestion, FieldFilePath;
    private JTextField[] FieldChoices;
    private JCheckBox FillInCheck;
    private JButton ButtonOk, ButtonBrowse;
    private JOptionPane AlertMessage;
    
    public QuestionEditor(String[] QuestionArray){
        
        /* Checks if the class is initiated to add a new question or edit an existing one
         * If the class is initiated in editor mode, QuestionId is parsed from String
         */
        
        isNew = (QuestionArray == null);
        if (!isNew){
            QuestionId = Integer.parseInt(QuestionArray[7]);
            multimedia = QuestionArray[6];
        }
        
        setupQuestionPanel();
        setupChoicesPanel();
        setupImagePanel();
        
        ButtonOk = new JButton("OK");
        ButtonOk.addActionListener(new ButtonOkHandler());
        addComponent(ButtonOk, 0, 5, 1, 1);
        
        if (QuestionArray != null){
            setValues(QuestionArray);
        }
        
        setSize(520, 500);
        setVisible(true);
    }
    
    private void setupQuestionPanel(){
    /* Makes and adds a titled border with question title, label and text field*/
        
        JPanel QuestionPanel = new JPanel();
        QuestionPanel.setLayout(new GridLayout(1, 2, 3, 3));
        QuestionPanel.setBorder(new TitledBorder("Question"));
        
        LabelQuestion = new JLabel("Question");
        LabelQuestion.setHorizontalAlignment(JLabel.CENTER);
        QuestionPanel.add(LabelQuestion);
        
        FieldQuestion = new JTextField(20);
        FieldQuestion.setToolTipText("Enter question here (compulsory)");
        QuestionPanel.setPreferredSize(new Dimension(500, 45));
        QuestionPanel.add(FieldQuestion);
        
        addComponent(QuestionPanel, 0, 0, 1, 1);
    }
    
    private void setupChoicesPanel(){
    /* Makes a titled panel with choices labels and
     * textfields as well as the fill-in checkbox
     */
        
        JPanel ChoicesPanel = new JPanel();
        ChoicesPanel.setLayout(new GridLayout(6, 2, 3, 3));
        ChoicesPanel.setBorder(new TitledBorder("Choices"));
        ChoicesPanel.setPreferredSize(new Dimension(500, 160));
        
        LabelChoices = new JLabel[5];
        FieldChoices = new JTextField[5];
        
        LabelChoices[0] = new JLabel("Choice A");
        LabelChoices[1] = new JLabel("Choice B");
        LabelChoices[2] = new JLabel("Choice C");
        LabelChoices[3] = new JLabel("Choice D");
        LabelChoices[4] = new JLabel("Choice E");
        
        for (int r = 0; r< FieldChoices.length; r++){
            LabelChoices[r].setHorizontalAlignment(JLabel.CENTER);
            ChoicesPanel.add(LabelChoices[r]);
            
            FieldChoices[r] = new JTextField(20);
            ChoicesPanel.add(FieldChoices[r]); 
        }
        FieldChoices[0].setToolTipText("Enter choice A here " +
                "(compulsory if the question is multiple choice)");
        FieldChoices[1].setToolTipText("Enter choice B here " +
                "(compulsory if the question is multiple choice)");
        FieldChoices[2].setToolTipText("Enter choice C here " +
                "(optional)");
        FieldChoices[3].setToolTipText("Enter choice D here (optional)");
        FieldChoices[4].setToolTipText("Enter choice E here (optional)");
        
        FillInCheck = new JCheckBox("Fill-in question");
        FillInCheck.setToolTipText("Check if the question is fill-in" +
                " (no choices needed in the case)");
        FillInCheck.addItemListener(new FillInCheckHandler());
        ChoicesPanel.add(FillInCheck);
        
        addComponent(ChoicesPanel, 0, 3, 1, 1);
    }
    
    private void setupImagePanel(){
    /* Makes and adds image panel with image preview label, 
     * path label and text field, browse button
     */    
        
        JPanel ImagePanel = new JPanel();
        ImagePanel.setPreferredSize(new Dimension(500, 200));
        ImagePanel.setLayout(new BorderLayout(3, 2));
        ImagePanel.setBorder(new TitledBorder("Image"));
        
        LabelLocation = new JLabel("File location");
        LabelLocation.setHorizontalAlignment(JLabel.CENTER);
        ImagePanel.add(LabelLocation, BorderLayout.WEST);
        
        FieldFilePath = new JTextField(20);
        FieldFilePath.setToolTipText("Enter absolute path to the image or click the " +
                "Browse key (optional)");
        FieldFilePath.addFocusListener(new FieldFilePathListener());
        ImagePanel.add(FieldFilePath, BorderLayout.CENTER);
        
        ButtonBrowse = new JButton("Browse...");
        ButtonBrowse.setToolTipText("Opens default file browser");
        ButtonBrowse.addActionListener(new ButtonBrowseHandler());
        ImagePanel.add(ButtonBrowse, BorderLayout.EAST);
        
        LabelImage = new JLabel("", new ImageIcon(""), SwingConstants.CENTER);
        LabelImage.setToolTipText("Preview");
        JScrollPane IconPane = new JScrollPane(LabelImage);
        IconPane.setPreferredSize(new Dimension(50, 150));
        IconPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        ImagePanel.add(IconPane, BorderLayout.SOUTH);
        
        addComponent(ImagePanel, 0, 4, 1, 1);
        
    }
    
    private void setValues(String[] values){
    /* If the class is launched in editor mode
     * this will set the existing values to text fields
     */    
        
        FieldQuestion.setText(values[0]);
        FieldFilePath.setText(values[6]);
        if(values[1].compareTo("") == 0){
            for (int r = 0; r <= 4; r++)
                FieldChoices[r].setEnabled(false);
            FillInCheck.setSelected(true);
        }
        else{
            for (int r = 1; r <= 5; r++)
                FieldChoices[r-1].setText(values[r]);
        }
        if (values[6].compareTo("") != 0)
            LabelImage.setIcon(new ImageIcon(conf.RootDirectory+values[6]));
    }
    
    private class FillInCheckHandler implements ItemListener{
    /* Disables and clears choices text fields */
        
        public void itemStateChanged(ItemEvent event){
            for (int r = 0; r<=4; r++){
                if (FillInCheck.isSelected()) {
                    FieldChoices[r].setText("");
                    FieldChoices[r].setEnabled(false);
                }
                else
                    FieldChoices[r].setEnabled(true);
            }
        }
    }
    
    public void FileChooserHandler(String FilePath){
    /* This method is called when the user clicks Open in file browser
     * Puts the FilePath obtained from FileChooser to the image file path
     */
        
        FieldFilePath.setText(FilePath);
        LabelImage.setIcon(new ImageIcon(FilePath));
    }
    
    private void AddQuestionToDB(String filename, String question, String[] choices){
    /* After the user clicks OK button, this method calls the methods, which
     * will add the new question to questions file and its id to questions index file
     */
        questions q = new questions();
        q.add_question(filename, question, choices);
    }
    
    private void UpdateDB(String image, String question, String[] choices){
    /* After editing of the question is complete, this following method 
     * calls methods, which update questions file
     */    
        questions q = new questions();
        
        try{
            q.update_question(QuestionId, image, question, choices);
        }
        catch(Exception e){
            System.err.println(e.toString());
        }
        
        if (image.compareTo("") != 0)
            admin.qt.updateQuestionsTableRow(question, choices, "yes");
        else
            admin.qt.updateQuestionsTableRow(question, choices, "no");
    }
    
    private class FieldFilePathListener implements FocusListener{
    /* When image path is enetered mannually, this listener will preview the image*/
        
        public void focusLost(FocusEvent evt){
            LabelImage.setIcon(new ImageIcon(FieldFilePath.getText()));
        }
        public void focusGained(FocusEvent evt){
            LabelImage.setIcon(null);
        }

    }
    
    private class ButtonOkHandler implements ActionListener{
    /* This Listener is launched after adding/editing question is complete */
        
        public void actionPerformed(ActionEvent e){
            
            String question = FieldQuestion.getText();
            String[] choices = new String[5];
            choices[0] = FieldChoices[0].getText();
            choices[1] = FieldChoices[1].getText();
            choices[2] = FieldChoices[2].getText();
            choices[3] = FieldChoices[3].getText();
            choices[4] = FieldChoices[4].getText();
            
            /* Checks if all required fields are filled in */
            if ((question.compareTo("") != 0) 
                && (((choices[0].compareTo("") != 0) && (choices[1].compareTo("") != 0))
                || (FillInCheck.isSelected()))){
                    admin.QEditor.dispose();
                    try{
                        if (isNew)
                            AddQuestionToDB(FieldFilePath.getText(), question, choices);
                        else
                            UpdateDB(FieldFilePath.getText(), question, choices);
                    }
                    catch(Exception e1){
                        System.err.println(e1.toString());
                    }
                    try{
                        if (isNew)
                            admin.qt.addQuestionsTableRow();    
                    }
                    catch(Exception e2){
                        System.out.println(e2.toString());
                    }
                }
                else{
                /* Alerts the user if he/she has not filled in all the required fields */
                    AlertMessage = new JOptionPane();
                    AlertMessage.showMessageDialog(null, "Please enter the question and" +
                            " at least two choices or check the fill-in checkbox");
                }
        }
    }
    
    private class ButtonBrowseHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
        /* Initiates browser class with images-only mode */
            FileChooser = new Browser(false);
        }
    }
}