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

class QuestionsTab extends application{
    
    public JPanel QuestionsTabPanel;
    
    public int[] questionsIndex;
    
    private JTable QuestionsTable;
    private DefaultTableModel QuestionsTableModel;
    private JPopupMenu jPopupMenu1;
    private JMenuItem jMenuItem1, jMenuItem2, jMenuItem3,  jMenuItem4;
    private JOptionPane AlertMessage;
    private JMenuBar jMenuBar1;
    private JMenu jMenu1;
    
    public QuestionsTab() throws IOException{
        
        QuestionsTabPanel = new JPanel();
        QuestionsTabPanel.setLayout(new BorderLayout(1, 2));
        
        this.setupPopUpMenu();
        this.setupQuestionsTable();
    }
    
    private void setupPopUpMenu(){
        
        jPopupMenu1 = new JPopupMenu();
        
        jMenuItem4 = new JMenuItem();
        jMenuItem4.setText("Edit");
        jMenuItem4.setToolTipText("Edit selected question, choices, add/remove/change image");
        jMenuItem4.addActionListener(new EditQuestionMenuHandler());
        jPopupMenu1.add(jMenuItem4);
        
        jPopupMenu1.addSeparator();
        
        jMenuItem1 = new JMenuItem();
        jMenuItem1.setText("Up a question");
        jMenuItem1.setToolTipText("Swaps the questions: selected question goes up a row");
        jMenuItem1.addActionListener(new UpQuestionMenuHandler());
        jPopupMenu1.add(jMenuItem1);
        
        jMenuItem2 = new JMenuItem();
        jMenuItem2.setText("Down a question");
        jMenuItem2.setToolTipText("Swaps the questions: selected question goes down a row");
        jMenuItem2.addActionListener(new DownQuestionMenuHandler());
        jPopupMenu1.add(jMenuItem2);
        
        jPopupMenu1.addSeparator();
        
        jMenuItem3 = new JMenuItem();
        jMenuItem3.setText("Remove");
        jMenuItem3.setToolTipText("Removes the question from the database");
        jMenuItem3.addActionListener(new RemoveQuestionMenuHandler());
        jPopupMenu1.add(jMenuItem3);
        
    }
    
    private void setupQuestionsTable() throws IOException{
        
        questions q = new questions();
        questionsIndex = q.get_line_order(q.index_filename);
        
        String ColumnNames[] = {"Question","Choice A","Choice B","Choice C","Choice D","Choice E", "Image"};
        String[][] ColumnValues =  q.get_all_questions(false);
        ColumnValues = setupImageColumn(ColumnValues);
        
        QuestionsTableModel = new DefaultTableModel(ColumnValues, ColumnNames);
        QuestionsTable = new JTable(QuestionsTableModel);
        QuestionsTable.setToolTipText("Select the question you want to edit and press the right mouse key for options");
        QuestionsTable.getColumnModel().getColumn(0).setPreferredWidth(400);
        QuestionsTable.setEnabled(true);
        QuestionsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        for (int r = 0; r < QuestionsTable.getColumnCount(); r++){
            TableColumn col = QuestionsTable.getColumnModel().getColumn(r);
            col.setCellEditor(new QuestionsTableCellEditor());
        }
        
        /*QuestionsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);*/
        QuestionsTable.setRequestFocusEnabled(false);
        QuestionsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                QuestionsTab.this.mouseClicked(evt);
            }
        });
        
        JButton addQuestionButton = new JButton("Add a new question");
        addQuestionButton.addActionListener(new addQuestionButtonHandler());
        QuestionsTabPanel.add(addQuestionButton, BorderLayout.NORTH);
        
        QuestionsTabPanel.add(new JScrollPane(QuestionsTable), BorderLayout.CENTER);
    }
    
    private String[][] setupImageColumn(String[][] ColumnValues){
        for (int r = 0; r<ColumnValues.length; r++){
            if (ColumnValues[r][6].compareTo("") != 0)
                ColumnValues[r][6] = "yes";
            else
                ColumnValues[r][6] = "no";
        }
        
        return ColumnValues;
    }
    
    public void addQuestionsTableRow() throws IOException{
        questions q = new questions();
        String[][] quest = q.get_all_questions(true);
        setupImageColumn(quest);
        QuestionsTableModel.addRow(quest[quest.length-1]);
        
        questionsIndex = q.get_line_order(q.index_filename);
    }
    
    public void updateQuestionsTableRow(String question, String[] choices, String image){
        QuestionsTableModel.setValueAt(question, QuestionsTable.getSelectedRow(), 0);
        QuestionsTableModel.setValueAt(image, QuestionsTable.getSelectedRow(), 6);
        for (int r = 0; r < 5; r++)
            QuestionsTableModel.setValueAt(choices[r], QuestionsTable.getSelectedRow(), r+1);
    }
    
    private void swapQuestions(int row1, int row2){
        int row = QuestionsTable.getSelectedRow();
        for(int column = 0; column < 7; column++){
            Object tmp = QuestionsTable.getValueAt(row1, column);
            QuestionsTable.setValueAt(QuestionsTable.getValueAt(row2, column), row1, column);
            QuestionsTable.setValueAt(tmp, row2, column);
        }
        
        int tmp = questionsIndex[row1];
        questionsIndex[row1] = questionsIndex[row2];
        questionsIndex[row2] = tmp;
        
        questions q = new questions();
        q.updateQuestionIndex(questionsIndex);
    }
    
    private void removeQuestions(int row){
        QuestionsTableModel.removeRow(row);
        for (int r = row; r<(questionsIndex.length-1); r++)
            questionsIndex[r] = questionsIndex[r+1];
        
        questionsIndex[questionsIndex.length-1] = -1;
       
        questions q = new questions();
        q.updateQuestionIndex(questionsIndex);        
    }
        
    private class UpQuestionMenuHandler implements ActionListener{
        public void actionPerformed(java.awt.event.ActionEvent e){
            swapQuestions(QuestionsTable.getSelectedRow(), QuestionsTable.getSelectedRow()-1);
            QuestionsTable.setRowSelectionInterval(QuestionsTable.getSelectedRow()-1, QuestionsTable.getSelectedRow()-1);
            
            jPopupMenu1.setVisible(false);
        }
       
    }
    
    private class DownQuestionMenuHandler implements ActionListener{
        public void actionPerformed(java.awt.event.ActionEvent e){
            jPopupMenu1.setVisible(false);
            
            swapQuestions(QuestionsTable.getSelectedRow()+1, QuestionsTable.getSelectedRow());
            QuestionsTable.setRowSelectionInterval(QuestionsTable.getSelectedRow()+1, QuestionsTable.getSelectedRow()+1);
        }
       
    } 
    
    private class RemoveQuestionMenuHandler implements ActionListener{
        public void actionPerformed(java.awt.event.ActionEvent e){
            jPopupMenu1.setVisible(false);
            
            AlertMessage = new JOptionPane();
            if(AlertMessage.showConfirmDialog(null, "Are you sure you want to remove this question?")== 0)
                removeQuestions(QuestionsTable.getSelectedRow());
        }
       
    }
    
    private class EditQuestionMenuHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            questions q = new questions();
            try{
                String[][] quest = q.get_all_questions(true);
                admin.QEditor = new QuestionEditor(quest[QuestionsTable.getSelectedRow()]);
            }
            catch(Exception e3){
                System.out.println(e.toString());
            }
            jPopupMenu1.setVisible(false);
        }
    }
    
    private void mouseClicked(MouseEvent evt) {
        
        int min = (QuestionsTable.getSelectedRow() * QuestionsTable.getRowHeight());
        int max = ((QuestionsTable.getSelectedRow() + 1) * QuestionsTable.getRowHeight());
        
        if (jPopupMenu1.isVisible())
            jPopupMenu1.setVisible(false);
        else if ((evt.getButton() == 3) && (QuestionsTable.getSelectedRow() != -1) && (evt.getY()>min) && (evt.getY()<max)){
            if (QuestionsTable.getSelectedRow() == 0)
                jMenuItem1.setEnabled(false);
            else
                jMenuItem1.setEnabled(true);
            
            if (QuestionsTable.getSelectedRow() == QuestionsTable.getRowCount()-1)
                jMenuItem2.setEnabled(false);
            else
                jMenuItem2.setEnabled(true);
            
            jPopupMenu1.setLocation(evt.getX()+admin.getX()+5, evt.getY()+admin.getY()+90);
            jPopupMenu1.setVisible(true);
            
        }
        else if ((evt.getButton() == 3) && (evt.getY()<min) || (evt.getY()>max)){
            AlertMessage = new JOptionPane();
            AlertMessage.showMessageDialog(null, "Please select the question you want to edit and click the right button for administration options.");
        }
        else if ((evt.getButton()==1) && (evt.getClickCount() ==2)){
            try{
                questions q = new questions();
                String[][] quest = q.get_all_questions(true);
                admin.QEditor = new QuestionEditor(quest[QuestionsTable.getSelectedRow()]);
            } catch (Exception e){
                System.out.println(e.toString());
            }
        }
    }
    
    private class addQuestionButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e){
            admin.QEditor = new QuestionEditor(null);
        }
    }
    
    private class QuestionsTableCellEditor extends AbstractCellEditor implements TableCellEditor {
        JComponent component = new JTextField();
        
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int rowIndex, int vColIndex) {
            
            return null;
        }
        
        public Object getCellEditorValue() {
            
            return null;
        }
    }    
}