/* This work has been placed into the public domain. */

package kiyut.alkitab.options;

import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import kiyut.alkitab.util.IOUtilities;
import org.crosswire.jsword.book.sword.SwordBookPath;

final class PathOptionsPanel extends javax.swing.JPanel {

    private final PathOptionsPanelController controller;
    private ResourceBundle bundle = ResourceBundle.getBundle(this.getClass().getName());

    PathOptionsPanel(PathOptionsPanelController controller) {
        this.controller = controller;
        initComponents();
        initCustom();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        bookPathList = new javax.swing.JList<>();
        jToolBar1 = new javax.swing.JToolBar();
        addPathButton = new javax.swing.JButton();
        removePathButton = new javax.swing.JButton();
        moveUpPathButton = new javax.swing.JButton();
        moveDownPathButton = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        downloadPathField = new javax.swing.JTextField();
        browseDownloadPathButton = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        currentConfigTextPane = new javax.swing.JTextPane();
        jLabel15 = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(24, 24, 24, 24));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        org.openide.awt.Mnemonics.setLocalizedText(jLabel14, bundle.getString("CTL_RequireRestart.Text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(jLabel14, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel10, bundle.getString("CTL_BookPath.Text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 12);
        jPanel1.add(jLabel10, gridBagConstraints);

        bookPathList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(bookPathList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0);
        jPanel1.add(jScrollPane1, gridBagConstraints);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        addPathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kiyut/alkitab/bookviewer/plus.png"))); // NOI18N
        addPathButton.setToolTipText(bundle.getString("CTL_AddPath.Text")); // NOI18N
        addPathButton.setFocusable(false);
        addPathButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addPathButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(addPathButton);

        removePathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kiyut/alkitab/bookviewer/minus.png"))); // NOI18N
        removePathButton.setToolTipText(bundle.getString("CTL_RemovePath.Text")); // NOI18N
        removePathButton.setFocusable(false);
        removePathButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removePathButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(removePathButton);

        moveUpPathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kiyut/alkitab/options/up.png"))); // NOI18N
        moveUpPathButton.setToolTipText(bundle.getString("CTL_MoveUpPath.Text")); // NOI18N
        moveUpPathButton.setFocusable(false);
        moveUpPathButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        moveUpPathButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(moveUpPathButton);

        moveDownPathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kiyut/alkitab/options/down.png"))); // NOI18N
        moveDownPathButton.setToolTipText(bundle.getString("CTL_MoveDownPath.Text")); // NOI18N
        moveDownPathButton.setFocusable(false);
        moveDownPathButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        moveDownPathButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(moveDownPathButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(jToolBar1, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel11, bundle.getString("CTL_DownloadPath.Text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 12);
        jPanel1.add(jLabel11, gridBagConstraints);

        jPanel6.setLayout(new java.awt.GridBagLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        jPanel6.add(downloadPathField, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(browseDownloadPathButton, bundle.getString("CTL_DownloadPathBrowse.Text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
        jPanel6.add(browseDownloadPathButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 0);
        jPanel1.add(jPanel6, gridBagConstraints);

        jPanel7.setLayout(new java.awt.GridBagLayout());

        currentConfigTextPane.setEditable(false);
        jScrollPane2.setViewportView(currentConfigTextPane);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 0);
        jPanel7.add(jScrollPane2, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel15, bundle.getString("CTL_CurrentConfig.Text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel7.add(jLabel15, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0);
        jPanel1.add(jPanel7, gridBagConstraints);

        add(jPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    void load() {
        BookViewerOptions bookViewerOpts = BookViewerOptions.getInstance();
        File path = bookViewerOpts.getDownloadPath();
        if (path != null) {
            downloadPathField.setText(path.getPath());
        }

        File[] paths = bookViewerOpts.getBookPaths();
        if (paths != null) {
            DefaultListModel<File> model = (DefaultListModel<File>)bookPathList.getModel();
            model.clear();
            for (int i=0; i <paths.length; i++) {
                model.addElement(paths[i]);
            }
        }

        // current config
        refreshCurrentConfig();
    }

    void store() {
        BookViewerOptions bookViewerOpts = BookViewerOptions.getInstance();

        String path = downloadPathField.getText().trim();
        if (path.length() > 0) {
            bookViewerOpts.setDownloadPath(new File(path));
        } else {
            bookViewerOpts.setDownloadPath(null);
        }

        File[] paths = new File[bookPathList.getModel().getSize()];
        for (int i=0; i < paths.length; i++) {
            paths[i] = bookPathList.getModel().getElementAt(i);
        }
        if (paths.length > 0) {
            bookViewerOpts.setBookPaths(paths);
        } else {
            bookViewerOpts.setBookPaths(null);
        }

        bookViewerOpts.store();
    }

    boolean valid() {
        return true;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addPathButton;
    private javax.swing.JList<File> bookPathList;
    private javax.swing.JButton browseDownloadPathButton;
    private javax.swing.JTextPane currentConfigTextPane;
    private javax.swing.JTextField downloadPathField;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton moveDownPathButton;
    private javax.swing.JButton moveUpPathButton;
    private javax.swing.JButton removePathButton;
    // End of variables declaration//GEN-END:variables

    private void initCustom() {
        bookPathList.setModel(new DefaultListModel<File>());
        bookPathList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // XXX workaround for Windows Plaf for button margin
        Insets insets = new Insets(0, 0, 0, 0);
        addPathButton.setMargin(insets);
        removePathButton.setMargin(insets);
        moveUpPathButton.setMargin(insets);
        moveDownPathButton.setMargin(insets);

        addPathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                JFileChooser fc = IOUtilities.getFileChooser();
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int choice = fc.showOpenDialog(PathOptionsPanel.this);
                if (choice != JFileChooser.APPROVE_OPTION) {
                    return;
                }
                File file = fc.getSelectedFile();
                boolean exists = false;
                for (int i=0; i<bookPathList.getModel().getSize(); i++) {
                    Object obj = bookPathList.getModel().getElementAt(i);
                    if (file.equals(obj)) {
                        Object[] args = {file.getPath()};
                        String msg = MessageFormat.format(bundle.getString("MSG_BookPathExists.Text"), args);
                        JOptionPane.showMessageDialog(PathOptionsPanel.this, msg , bundle.getString("CTL_BookPath.Text"), JOptionPane.ERROR_MESSAGE);
                        exists = true;
                        break;
                    }
                }

                if (!exists) {
                    ((DefaultListModel<File>) bookPathList.getModel()).addElement(file);
                }
            }
        });

        removePathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                int i = bookPathList.getSelectedIndex();
                if (i < 0) {
                    return;
                }
                ((DefaultListModel) bookPathList.getModel()).remove(i);
            }
        });

        moveUpPathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                int i = bookPathList.getSelectedIndex();
                if (i <= 0) {
                    return;
                }
                DefaultListModel<File> listModel = (DefaultListModel<File>)bookPathList.getModel();
                File file = listModel.remove(i);
                i = i - 1;
                listModel.add(i, file);
                bookPathList.setSelectedIndex(i);
            }
        });

        moveDownPathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt)  {
                if (bookPathList.getModel().getSize() < 2) { return; }
                int i = bookPathList.getSelectedIndex();
                if (i < 0 ) { return; }
                DefaultListModel<File> listModel = (DefaultListModel<File>)bookPathList.getModel();
                File file = listModel.remove(i);
                if (i < bookPathList.getModel().getSize()) {
                    listModel.add(i+1, file);
                    i = i + 1;
                } else {
                    listModel.addElement(file);
                    i = bookPathList.getModel().getSize() - 1;
                }
                bookPathList.setSelectedIndex(i);
            }
        });

        browseDownloadPathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                JFileChooser fc = IOUtilities.getFileChooser();
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int choice = fc.showOpenDialog(PathOptionsPanel.this);
                if (choice != JFileChooser.APPROVE_OPTION) {
                    return;
                }
                File file = fc.getSelectedFile();
                downloadPathField.setText(file.getPath());
            }
        });
    }

    protected void refreshCurrentConfig() {
        StringBuilder sb = new StringBuilder();
        File[] files = SwordBookPath.getSwordPath();
        for (int i=0; i<files.length; i++) {
            sb.append(files[i].toString()).append("\n");
        }
        currentConfigTextPane.setText(sb.toString());
    }
}
