package hiro.yoshioka.sdh;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;

public class CSVDataHolderTransfer extends ByteArrayTransfer {

	private static final String MYTYPENAME = "CSVDataHolder";

	private static final int MYTYPEID = registerType(MYTYPENAME);

	private static CSVDataHolderTransfer instance = new CSVDataHolderTransfer();

	public CSVDataHolderTransfer() {
	}

	public static CSVDataHolderTransfer getInstance() {
		return instance;
	}

	public void javaToNative(Object object, TransferData transferData) {
		if (object == null || !(object instanceof CSVRecordDataHolder)) {
			return;
		}
		if (isSupportedType(transferData)) {
			CSVRecordDataHolder rdh = (CSVRecordDataHolder) object;
			try {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				ObjectOutputStream os = new ObjectOutputStream(out);
				os.writeObject(rdh);
				byte[] buffer = out.toByteArray();
				os.flush();
				os.close();
				super.javaToNative(buffer, transferData);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public Object nativeToJava(TransferData transferData) {
		if (isSupportedType(transferData)) {
			byte[] buffer = (byte[]) super.nativeToJava(transferData);
			if (buffer == null) {
				return null;
			}
			CSVRecordDataHolder cdh;
			try {
				ByteArrayInputStream in = new ByteArrayInputStream(buffer);
				ObjectInputStream os = new ObjectInputStream(in);
				cdh = (CSVRecordDataHolder) os.readObject();
				os.close();
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
			return cdh;
		}
		return null;
	}

	protected String[] getTypeNames() {
		return new String[] { MYTYPENAME };
	}

	protected int[] getTypeIds() {
		return new int[] { MYTYPEID };
	}
}
