package hiro.yoshioka.sql.resource;

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

	private static final String MYTYPENAME = "DBResource";

	private static final int MYTYPEID = registerType(MYTYPENAME);

	private static DBResourceTransfer instance = new DBResourceTransfer();

	public DBResourceTransfer() {
	}

	public static DBResourceTransfer getInstance() {
		return instance;
	}

	// シリアライズ
	public void javaToNative(Object object, TransferData transferData) {
		if (object == null) {
			return;
		}
		System.out.println("object=  " + object.getClass() );
		if ((object instanceof DBResource) || (object instanceof DBResource[])) {
		} else {
			return;
		}

		if (isSupportedType(transferData)) {
			try {
				if (object instanceof DBResource[]) {
					System.out.println("object=  instanceof DBResource[]" );
					DBResource[] rdh = (DBResource[]) object;
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					ObjectOutputStream os = new ObjectOutputStream(out);
					os.writeObject(rdh);
					byte[] buffer = out.toByteArray();
					os.flush();
					os.close();
					super.javaToNative(buffer, transferData);
				} else if (object instanceof DBResource) {
					System.out.println("object=  instanceof DBResource" );
					DBResource[] rdh = new DBResource[] { (DBResource) object };
					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;
			}
			Object o;
			try {
				ByteArrayInputStream in = new ByteArrayInputStream(buffer);
				ObjectInputStream os = new ObjectInputStream(in);
				o = os.readObject();
				os.close();
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
			return o;
		}
		return null;
	}

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

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