import java.awt.*;
import java.io.IOException;
import java.awt.datatransfer.*;
import javax.swing.*;

/**
 * A TransferHandler that supports DnD and CCP on Component objects
 * that implement the ImageTransferer interface.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ImageTransferHandler extends TransferHandler
{
  private static final long serialVersionUID = 1L;

  private boolean         shouldCutWhenDone;
  private ImageTransferer 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)) 
    {
      ImageTransferer component = (ImageTransferer)c;
      try 
      {
        Image image = (Image)t.getTransferData(ImageSelection.IMAGE_FLAVOR);
        component.setImage(image);
        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) 
  {
    ImageTransferer component = (ImageTransferer)c;
    source = component;
    shouldCutWhenDone = true; // By default
    return new ImageSelection(component.getImage());
  }

  /**
   * 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) 
  {
    return COPY_OR_MOVE;
  }

  /**
   * 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)
    {
      ImageTransferer component = (ImageTransferer)c;
      component.setImage(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(ImageSelection.IMAGE_FLAVOR)) return true;
    }
    return false;
  }
}
