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 ResultSetDataHolderTransfer extends ByteArrayTransfer {

	private static final String MYTYPENAME = "ResultSetDataHolder";

	private static final int MYTYPEID = registerType(MYTYPENAME);

	private static ResultSetDataHolderTransfer instance = new ResultSetDataHolderTransfer();

	public ResultSetDataHolderTransfer() {
	}

	public static ResultSetDataHolderTransfer getInstance() {
		return instance;
	}

	// シリアライズ
	public void javaToNative(Object object, TransferData transferData) {
		if (object == null || !(object instanceof ResultSetDataHolder)) {
			return;
		}
		if (isSupportedType(transferData)) {
			ResultSetDataHolder rdh = (ResultSetDataHolder) 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;
			}
			ResultSetDataHolder rdh;
			try {
				ByteArrayInputStream in = new ByteArrayInputStream(buffer);
				ObjectInputStream os = new ObjectInputStream(in);
				rdh = (ResultSetDataHolder) os.readObject();
				os.close();
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
			return rdh;
		}
		return null;
	}

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

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