import java.io.IOException;
import java.awt.datatransfer.*;
import javax.swing.*;

/**
 * A TransferHandler that supports DnD (both Copy and Move) of String objects.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class StringTransferHandler extends TransferHandler
{
  private static final long serialVersionUID = 1L;

  private boolean         shouldCutWhenDone;
  private StringCollage   source;
  
  /**
   * Import the Transferable in the TransferSupport into the
   * JComponent in the TransferSupport.
   * 
   * @param support  The TransferSupport
   * @return true if the data was imported; false otherwise
   */
  public boolean importData(TransferHandler.TransferSupport support)
  {
    JComponent c = (JComponent)support.getComponent();
    Transferable t = support.getTransferable();
    
    shouldCutWhenDone = false;
    
    if ((source != c) && canImport(support)) 
    {
      StringCollage component = (StringCollage)c;
      try 
      {
        String text = (String)t.getTransferData(DataFlavor.stringFlavor);
        component.setText(text);
        shouldCutWhenDone = true;
        return true;
      } 
      catch (IOException | UnsupportedFlavorException e) 
      {
        return false;
      }
    }
    return false;
  }

  /**
   * Create a Transferable using the contents of the given JComponent.
   * 
   */
  protected Transferable createTransferable(JComponent c) 
  {
    StringCollage component = (StringCollage)c;
    
    source = component;
    shouldCutWhenDone = true; // By default
    return new StringSelection(component.getText());
  }

  /**
   * Get the source actions supported by this TransferHandler
   * for the given Component.
   * 
   * @param c  The Component of interest
   * @return   The source actions supported (COPY_OR_MOVE)
   */
  public int getSourceActions(JComponent c) 
  {
    StringCollage component = (StringCollage)c;
    
    source = component;
    return component.getAction();
  }

  /**
   * Complete the export process.
   * 
   * @param c      The Component
   * @param data   The Transferable
   * @param action The action
   */
  protected void exportDone(JComponent c, Transferable data, int action) 
  {
    if ((action == MOVE) && shouldCutWhenDone)
    {
      StringCollage component = (StringCollage)c;
      component.setText(null);
    }
    source = null;
  }

  /**
   * Return true if the Component in the TransferSupport can support one of the 
   * DataFlavor objects in the TransferSupport.
   * 
   * @param support  The TransferSupport
   */
  public boolean canImport(TransferHandler.TransferSupport support)
  {
    DataFlavor[] flavors = support.getDataFlavors();
    
    for (DataFlavor flavor: flavors)
    {
      if (flavor.equals(DataFlavor.stringFlavor)) return true;
    }
    return false;
  }
}
