/*
 * PGobjectHandler.java
 * 
 * (C) 28.02.2005 Markus Schaber, Logi-Track ag, CH 8001 Zuerich
 * 
 * $Id: $
 */
package org.postgresql.types;

import org.postgresql.util.PGobject;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;

public class PGobjectHandler extends AbstractTextTypeDriver {

    public PGobjectHandler(String sqltype, Class klass) {
        this.supportedClasses = new Class[]{klass};
        this.supportedTypes = new String[]{sqltype};
    }

    public String sqlType(Object data) throws SQLException {
        PGobject po = (PGobject) data;
        return po.getType();
    }

    public int objectCharLength(Object data) throws SQLException {
        PGobject po = (PGobject) data;
        return po.getValue().length();
    }

    public String renderObject(Object data) {
        PGobject po = (PGobject) data;
        return po.getValue();
    }

    public String getString(String data) throws SQLException {
        return data;
    }

    public Object getObject(String data) throws SQLException {
        PGobject po;
        try {
            po = (PGobject) supportedClasses[0].newInstance();
        } catch (InstantiationException e) {
            throw new SQLException("Cannot create PGObject instance " + e.getMessage());
        } catch (IllegalAccessException e) {
            throw new SQLException("Cannot create PGObject instance " + e.getMessage());
        }
        po.setValue(data);
        return po;
    }

    public void renderObject(Object data, StringBuffer sb) {
        sb.append(renderObject(data));
    }

    public void renderObject(Object data, char[] target, int startindex) {
        String rep = renderObject(data);
        for (int i = 0; i < rep.length(); i++) {
            target[i + startindex] = rep.charAt(i);
        }
    }

    public void renderObject(Object data, Writer target) throws IOException {
        target.write(renderObject(data));
    }
}
