/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.dragdrop;

import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class DragDropExample extends JPanel {
	DragDropExample() {
		super(new BorderLayout());

		final JList<String> list = new JList<>(new String[]{"A", "B", "C"});
		list.setLayoutOrientation(JList.VERTICAL);
		list.setDragEnabled(true);
		list.setTransferHandler(new TransferHandler() {
			@Override
			public int getSourceActions(JComponent c) {
				return TransferHandler.COPY;
			}


			@Override
			protected Transferable createTransferable(JComponent c) {
				return new StringSelection(((JList<String>) c).getSelectedValue());
			}

			@Override
			protected void exportDone(JComponent source, Transferable data, int action) {
				if (action == TransferHandler.COPY) {
					System.out.println("Copy done.");
				}
			}
		});

		final JTextArea textArea = new JTextArea( " ");
		textArea.setDropMode(DropMode.INSERT);
		textArea.setTransferHandler(new TransferHandler() {
			@Override
			public boolean importData(TransferSupport support) {
				if (!canImport(support)) {
					return false;
				}
				try {
					Transferable transferable = support.getTransferable();
					String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);

					JTextComponent.DropLocation dropLocation = (JTextComponent.DropLocation) support.getDropLocation();
					int idx = dropLocation.getIndex();

					textArea.insert(data, idx);
					return true;
				} catch (UnsupportedFlavorException | IOException e) {
					throw new RuntimeException(e);
				}
			}

			@Override
			public boolean canImport(TransferSupport support) {
				if (support.isDataFlavorSupported(DataFlavor.stringFlavor) &&
				(support.getSourceDropActions() & COPY)==COPY) {
					support.setDropAction(COPY);
					return true;
				} else {
					return false;
				}
			}
		});

		list.setMinimumSize(new Dimension(300, 0));
		add(list, BorderLayout.LINE_START);
		add(textArea, BorderLayout.CENTER);
	}

	public static void main(String... args) {

		// 프레임을 생성한다.
		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new DragDropExample());

		// 이벤트 디스패치 스레드에서 프레임을 표시한다.
		SwingUtilities.invokeLater(() -> {
			jFrame.setVisible(true);
		});


	}
}
