package daruma.geometry;

import daruma.geometry.DrmGeometry;
import daruma.geometry.DrmPoint;
import java.util.regex.*;

import com.vividsolutions.jts.geom.* ;
import com.vividsolutions.jts.geom.impl.* ;
import daruma.geometry.OgcGeometryFactory ;


//======================================================================
/**
 * DrmEnvelope クラス。
 * boundedBy 等で利用。
 */
public class DrmEnvelope extends DrmGeometry
{
    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    private DrmPoint pointNE;
    private DrmPoint pointSW;

    //------------------------------------------------------------
    /**
     * constructor
     */
    public DrmEnvelope(DrmPoint pointNE, DrmPoint pointSW) {
	set(pointNE, pointSW) ;
    }
    
    public DrmEnvelope(double x0, double y0, double x1, double y1) {
	this.pointNE = new DrmPoint(0.0,0.0) ;
	this.pointSW = new DrmPoint(0.0,0.0) ;
	set(x0, y0, x1, y1) ;
    }

    //------------------------------------------------------------
    /**
     * set values
     */
    public DrmEnvelope set(DrmPoint pointNE, DrmPoint pointSW) {
	this.pointNE = pointNE ;
	this.pointSW = pointSW ;
	return this ;
    }
    
    public DrmEnvelope set(double x0, double y0, double x1, double y1) {
	this.pointNE = new DrmPoint(x0, y0) ;
	this.pointSW = new DrmPoint(x1, y1) ;
	return this ;
    }
    
    //------------------------------------------------------------
    /**
     * access
     */
    public DrmPoint getPointNE() {
	return this.pointNE ;
    }

    public DrmPoint getPointSW() {
	return this.pointSW ;
    }

    //------------------------------------------------------------
    /**
     * scanner
     */
    public static DrmEnvelope scanPolygonWKT(String wktString) 
	throws Exception
    {
	Pattern polygonPattern = 
	    Pattern.compile("POLYGON\\(\\(([-\\.\\d ,]+)\\)\\)") ;
	Matcher polygonMatcher =
	    polygonPattern.matcher(wktString) ;
	if(!polygonMatcher.matches()) {
	    throw new Exception
		("Illegal Response for boundedBy query. Result String="
		 + wktString) ;
	} 
	String coordStr =
	    polygonMatcher.group(1) ;
		
	String[] xyCoords = coordStr.split(",") ;
	String[] xyCoord0 = xyCoords[0].split(" ") ;
	String[] xyCoord1 = xyCoords[2].split(" ") ;
	    
	double x0 = Double.valueOf(xyCoord0[0]) ;
	double y0 = Double.valueOf(xyCoord0[1]) ;
	double x1 = Double.valueOf(xyCoord1[0]) ;
	double y1 = Double.valueOf(xyCoord1[1]) ;

	return new DrmEnvelope(x0, y0, x1, y1) ;
    }

    @Override
    public DrmEnvelope transform( CoordinateSystemTransformation trans )
	    throws TransformationException
    {
	return new DrmEnvelope( trans.transform( pointNE ) ,
				trans.transform( pointSW ) );
    }

    //------------------------------------------------------------
    /**
     * geometry generator
     */
    @Override
    public Geometry genGeometry(OgcGeometryFactory geoFactory) {
	// FIXME: should be implemented
	return null ;
    }
}
