/*
 * Testclass.java Created on 12.03.2004 09:25:30 by schabi
 * 
 * $Id: JtsGeometry.java,v 1.3 2004/07/16 15:14:28 schabi Exp $
 * 
 * (C) 2004 Markus Schaber, logi-track ag, Zürich, Switzerland
 * 
 * This file currently is beta test code and licensed under the GNU LGPL. If you
 * need different license terms, you have to contact logi-track ag.
 */
package com.logitrack.gis.util;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKTReader;

import org.postgresql.util.PGobject;

import java.sql.SQLException;

/**
 * JTS Geometry SQL wrapper
 * 
 * @author Markus Schaber
 */

public class JtsGeometry extends PGobject {

    Geometry geom;

    final static WKTReader reader = new WKTReader();

    public JtsGeometry() {
        //Constructor called by JDBC drivers
    }

    public JtsGeometry(Geometry geom) {
        this.geom = geom;
    }

    public JtsGeometry(String value) throws SQLException {
        setValue(value);
    }

    public void setValue(String value) throws SQLException {
        geom = geomFromString(value);
    }

    public static Geometry geomFromString(String value) throws SQLException {
        try {
            value = value.trim();
            if (value.startsWith("SRID")) {
                value = value.split(";")[1];
            }
            //break up geometry into srid and wkt
            return reader.read(value);
        } catch (Exception E) {
            throw new SQLException("Error parsing SQL data:" + E);
        }
    }

    public Geometry getGeometry() {
        return geom;
    }

    public String toString() {
        return geom.toString();
    }

    public String getValue() {
        return geom.toString();
    }

    public Object clone() {
        JtsGeometry obj = new JtsGeometry(geom);
        obj.setType(type);
        return obj;
    }
    
    public boolean equals(Object obj)
    {
        if (obj instanceof JtsGeometry)            
            return ((JtsGeometry)obj).getValue().equals(geom);
        return false;
    }
}