/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.interactive.ivaap.data.crs.apachesis;

import org.apache.sis.geometry.DirectPosition2D;
import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox;
import org.apache.sis.referencing.CRS;
import org.apache.sis.referencing.crs.AbstractCRS;
import org.apache.sis.referencing.cs.AxesConvention;
import org.opengis.geometry.DirectPosition;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.CoordinateOperation;
import org.opengis.referencing.operation.MathTransform;

/**
 *
 * @author Thierry
 */
public class ExtentUtil {

    public static DefaultGeographicBoundingBox getExtentFromAreaOfUse(CoordinateReferenceSystem displayOrientedFromCrs,
            double minX, double minY, double maxX, double maxY) throws Exception {
        CoordinateReferenceSystem toCrs = CRS.forCode("EPSG:4326");
        AbstractCRS displayOrientedToCrs = AbstractCRS.castOrCopy(toCrs).forConvention(AxesConvention.DISPLAY_ORIENTED); // longitude should be first
        CoordinateOperation operation = CRS.findOperation(displayOrientedFromCrs, displayOrientedToCrs, null);
        MathTransform mt = operation.getMathTransform();
        DirectPosition topLeftPosition = new DirectPosition2D(minX, maxY);
        DirectPosition topRightPosition = new DirectPosition2D(maxX, maxY);
        DirectPosition bottomRightPosition = new DirectPosition2D(maxX, minY);
        DirectPosition bottomLeftPosition = new DirectPosition2D(minX, minY);
        DirectPosition topLeftLatLongPosition = mt.transform(topLeftPosition, topLeftPosition);
        DirectPosition topRightLatLongPosition = mt.transform(topRightPosition, topRightPosition);
        DirectPosition bottomLeftLatLongPosition = mt.transform(bottomLeftPosition, bottomLeftPosition);
        DirectPosition bottomRightLatLongPosition = mt.transform(bottomRightPosition, bottomRightPosition);
        double westBoundLongitude = Math.min(topLeftLatLongPosition.getCoordinate()[0], bottomLeftLatLongPosition.getCoordinate()[0]);
        double eastBoundLongitude = Math.max(topLeftLatLongPosition.getCoordinate()[0], bottomLeftLatLongPosition.getCoordinate()[0]);
        double southBoundLatitude = Math.min(topRightLatLongPosition.getCoordinate()[1], bottomRightLatLongPosition.getCoordinate()[1]);
        double northBoundLatitude = Math.max(topRightLatLongPosition.getCoordinate()[1], bottomRightLatLongPosition.getCoordinate()[1]);
        return new DefaultGeographicBoundingBox(westBoundLongitude, eastBoundLongitude, southBoundLatitude, northBoundLatitude);
    }

}
