package lu.tudor.santec.gecamed.core.gui.controller.data;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;


public class TextTransferable implements Transferable 
{
	/* ======================================== */
	// 		FINAL MEMBERS
	/* ======================================== */
	
	public static final int TEXT_TRANSFERABLE = 0;
	public static final int HTML_TRANSFERABLE = 1;
	
	private static final ArrayList<DataFlavor> textFlavors = new ArrayList<DataFlavor>();
	
	static 
	{
		try 
		{
			textFlavors.add(new DataFlavor("text/plain;class=java.lang.String"));
			textFlavors.add(new DataFlavor("text/plain;class=java.io.Reader"));
			textFlavors.add(new DataFlavor("text/plain;charset=unicode;class=java.io.InputStream"));
		} 
		catch (ClassNotFoundException ex) 
		{
			ex.printStackTrace();
		}
	}
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	protected String text;
	
	protected ArrayList<DataFlavor> flavors = textFlavors;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTOR
	/* ======================================== */
	
	public TextTransferable () 
	{
		this(null);
	}
	
	public TextTransferable (String text)
	{
		setText(text);
	}
	
	
	
	/* ======================================== */
	// 		GETTER & SETTER
	/* ======================================== */
	
	public void setText (String text)
	{
		if (text == null)
			this.text = "";
		else
			this.text = text;
	}
	
	public String getText ()
	{
		return this.text;
	}
	
	public DataFlavor[] getTransferDataFlavors() 
	{
		return (DataFlavor[]) flavors.toArray(new DataFlavor[flavors.size()]);
	}
	
	public boolean isDataFlavorSupported(DataFlavor flavor) 
	{
		return flavors.contains(flavor);
	}
	
	public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException 
	{
		if (String.class.equals(flavor.getRepresentationClass())) 
			return text;
		else if (Reader.class.equals(flavor.getRepresentationClass())) 
			return new StringReader(text);
		else if (InputStream.class.equals(flavor.getRepresentationClass())) 
			return new ByteArrayInputStream(text.getBytes());
		else
			throw new UnsupportedFlavorException(flavor);
	}
} 
