package yukihane.inqubus.gui;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JCheckBox;
import javax.swing.TransferHandler;
import javax.swing.text.JTextComponent;

/**
 * メイン画面の動画/コメント入力フィールド用TransferHandler
 * @author yuki
 */
class ContentTransferHandler extends TransferHandler {

    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(ContentTransferHandler.class);
    private final JCheckBox cbLocal;
    private final TransferHandler defaultTransferHandler;

    /**
     *
     * @param defaultTransferHandler 対象JTextFieldインスタンスのデフォルトtransfer handler.
     * @param cbLocal 対応するローカルチェックボックス.
     */
    ContentTransferHandler(TransferHandler defaultTransferHandler, JCheckBox cbLocal) {
        this.defaultTransferHandler = defaultTransferHandler;
        this.cbLocal = cbLocal;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {
        if (!cbLocal.isSelected()) {
            return defaultTransferHandler.canImport(support);
        }

        if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
                && !support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            return false;
        }

        if (support.isDrop()) {
            support.setDropAction(LINK);
        }
        return true;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport support) {
        if (!cbLocal.isSelected() || !support.isDrop()) {
            return defaultTransferHandler.importData(support);
        }

        final Transferable tr = support.getTransferable();
        try {
            String text;
            if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                @SuppressWarnings("unchecked")
                final List<File> files = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
                if (files.size() > 0) {
                    File file = files.get(0);
                    text = file.getPath();
                } else {
                    text = "";
                }
            } else if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                text = (String) tr.getTransferData(DataFlavor.stringFlavor);
            } else {
                return false;
            }
            final JTextComponent comp = (JTextComponent) support.getComponent();
            comp.setText(text);
            return true;
        } catch (UnsupportedFlavorException | IOException ex) {
            logger.error(null, ex);
        }
        return false;
    }
}
