package yukihane.inqubus.gui;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.TransferHandler;

/**
 *
 * @author yuki
 */
class DirectoryRegisterPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private final DefaultListModel<String> mdlSearchVideo = new DefaultListModel<>();
    private final JList<String> lstSearchVideo = new JList<>(mdlSearchVideo);
    private final JButton btnSearchVideoAdd = new JButton("追加...");
    private final JButton btnSearchVideoDel = new JButton("削除");

    List<String> getAllElements() {
        List<String> res = new ArrayList<>(mdlSearchVideo.getSize());
        for (int i = 0; i < mdlSearchVideo.getSize(); i++) {
            res.add(mdlSearchVideo.get(i));
        }
        return res;
    }

    void init(List<String> dirs) {
        mdlSearchVideo.clear();
        for (String s : dirs) {
            mdlSearchVideo.addElement(s);
        }
    }

    DirectoryRegisterPanel() {
        lstSearchVideo.setTransferHandler(new DirectoryTransferHandler(mdlSearchVideo));
        btnSearchVideoAdd.addActionListener(new AddActionListener());
        btnSearchVideoDel.addActionListener(new DelActionListener());

        final JScrollPane srcSearchVideo = new JScrollPane();
        srcSearchVideo.setViewportView(lstSearchVideo);

        GroupLayout gl_pnlSearchVideo = new GroupLayout(this);
        setLayout(gl_pnlSearchVideo);
        gl_pnlSearchVideo.setHorizontalGroup(
            gl_pnlSearchVideo.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(srcSearchVideo, GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
            .addGroup(GroupLayout.Alignment.TRAILING, gl_pnlSearchVideo.createSequentialGroup()
                .addContainerGap(269, Short.MAX_VALUE)
                .addComponent(btnSearchVideoAdd)
                .addGap(18, 18, 18)
                .addComponent(btnSearchVideoDel)
                .addContainerGap())
        );
        gl_pnlSearchVideo.setVerticalGroup(
            gl_pnlSearchVideo.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(gl_pnlSearchVideo.createSequentialGroup()
                .addComponent(srcSearchVideo, GroupLayout.PREFERRED_SIZE, 100, Short.MAX_VALUE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addGroup(gl_pnlSearchVideo.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSearchVideoDel)
                    .addComponent(btnSearchVideoAdd))
            )
        );
    }

    private class AddActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser ch = new JFileChooser();
            ch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            final int selected = ch.showOpenDialog(DirectoryRegisterPanel.this);
            if (selected == JFileChooser.APPROVE_OPTION) {
                final File dir = ch.getSelectedFile();
                mdlSearchVideo.addElement(dir.getPath());
            }
        }
    }

    private class DelActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            final int idx = lstSearchVideo.getSelectedIndex();
            mdlSearchVideo.removeElementAt(idx);
        }
    }
}

class DirectoryTransferHandler extends TransferHandler {

    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(DirectoryTransferHandler.class);
    private final DefaultListModel<String> model;

    DirectoryTransferHandler(DefaultListModel<String> model) {
        this.model = model;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {
        Transferable transferable = support.getTransferable();
        if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport support) {
        boolean res = false;
        try {
            Transferable transferable = support.getTransferable();
            if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                @SuppressWarnings("unchecked")
                final List<File> data = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                for (File f : data) {
                    if (f.isDirectory()) {
                        model.addElement(f.getPath());
                        res = true;
                    }
                }
            }
            return res;
        } catch (UnsupportedFlavorException | IOException e) {
            logger.error(null, e);
            return res;
        }
    }
}
