
/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 *
 * This software is a multi-platform and portable application based on
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s
 * possible to calculate indicators «RhoMéO» to monitor quality,
 * fonctionalities and urban and agricultural pressures of wetlands.
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 *
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use,
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info".
 *
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability.
 *
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or
 * data to be ensured and,  more generally, to use and operate it in the
 * same conditions as regards security.
 *
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.protocol.p08;

import fr.cenra.rhomeo.core.data.reference.GeoReferential;
import fr.cenra.rhomeo.core.data.reference.GeoReferentials;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import fr.cenra.rhomeo.api.data.Site;
import fr.cenra.rhomeo.api.process.Indicator;
import fr.cenra.rhomeo.api.process.ProcessContext;
import fr.cenra.rhomeo.api.result.Index;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import fr.cenra.rhomeo.api.process.Process;
import fr.cenra.rhomeo.core.util.GeometryUtils;
import java.io.IOException;
import org.apache.sis.storage.DataStoreException;
import org.geotoolkit.data.FeatureCollection;
import org.geotoolkit.data.FeatureIterator;
import org.geotoolkit.feature.Feature;

/**
 *
 *
 * @author Johann Sorel (Geomatys)
 */
public class I12Process extends Process {

    private final I12 indicator;

    @Autowired
    private GeoReferentials georefs;

    private final List<Integer> years = new ArrayList<>();

    public I12Process(ProcessContext context, I12 indicator){
        super(context);
        this.indicator = indicator;
    }

    @Override
    public Indicator getIndicator() {
        return indicator;
    }

    public List<Integer> getYears() {
        return years;
    }

    @Override
    protected Set<? extends Index> call() throws Exception {
        final Set<Index> indexes = new HashSet<>();

        for(Integer year : years){
            process(year,indexes);
        }

        return indexes;
    }

    private void process(int year, Set<Index> indexes) throws IOException, DataStoreException {

        final Site site = ctx.getDataCtx().getSite();
        final MultiPolygon siteGeom = ctx.getDataCtx().getSite().getGeometry();
        final Geometry siteGeomBuffer = GeometryUtils.computeBuffer(siteGeom);
        final double siteGeomBufferArea = siteGeomBuffer.getArea();
        final GeoReferential georef = georefs.getLocalReferential(site, year);

        /* =====================================================================
        bv AS (
            SELECT
		sites.id_site,
		st_area(sites.geom) AS surf_site,
                st_area(st_union(carthage_zh.geom)) AS area_bv,
                st_union(carthage_zh.geom) AS geom_bv
            FROM referentiels_geo.carthage_zh, expertise.sites
            WHERE st_intersects(sites.geom, carthage_zh.geom)
            GROUP BY sites.id_site
            ),
        */
        final Geometry geom_bv = georef
                .unionIntersecting(GeoReferentials.TYPE_ZONE_HYDRO, siteGeomBuffer)
                .orElseThrow(() -> new IllegalStateException("Aucune zone hydrographique valide."));

        final double area_bv = geom_bv.getArea();

        /* =====================================================================
        urb_bv AS (
            SELECT
		bv.id_site,
                round(bv.surf_site::numeric, 2) AS surf_site,
                round((sum(st_area2d(st_intersection(tache_urbaine.geom, bv.geom_bv))) * 100::double precision / bv.area_bv)::numeric, 2) AS urb_bv,
                bv.area_bv,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '4'::text
                    THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, bv.geom_bv))) * 100::double precision / bv.area_bv)::numeric, 2)
                    ELSE NULL::numeric
                END AS pdense_bv,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '5'::text
                    THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, bv.geom_bv))) * 100::double precision / bv.area_bv)::numeric, 2)
                    ELSE NULL::numeric
                END AS dense_bv,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '6'::text
                    THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, bv.geom_bv))) * 100::double precision / bv.area_bv)::numeric, 2)
                    ELSE NULL::numeric
                END AS tdense_bv
            FROM referentiels_geo.tache_urbaine,bv
            WHERE st_intersects(tache_urbaine.geom, bv.geom_bv)
                AND "left"(tache_urbaine.reclasse::text, 1)::integer > 3
            GROUP BY bv.id_site, bv.surf_site, bv.area_bv, tache_urbaine.reclasse, bv.geom_bv
            ),
        */

        /* =====================================================================
        bv_urb AS (
            SELECT
		urb_bv.id_site,
		max(urb_bv.pdense_bv) AS pdense_bv,
                max(urb_bv.dense_bv) AS dense_bv,
                max(urb_bv.tdense_bv) AS tdense_bv,
                sum(urb_bv.urb_bv) AS urba_bv,
                urb_bv.area_bv,
                urb_bv.surf_site
            FROM urb_bv
            GROUP BY urb_bv.id_site, urb_bv.area_bv, urb_bv.surf_site
            ),
        */
        double pdense_bv = 0;
        double dense_bv = 0;
        double tdense_bv = 0;
        double urba_bv = 0;

        final FeatureCollection tacheUrbaine = georef.getFeatureCollection(GeoReferentials.TYPE_TACHE_URBAINE, geom_bv);
        try(FeatureIterator ite = tacheUrbaine.iterator()){
            while(ite.hasNext()){
                final Feature feature = ite.next();
                final Geometry geom = (Geometry) feature.getDefaultGeometryProperty().getValue();

                final double intersectArea = geom_bv.intersection(geom).getArea();

                final String reclasse = String.valueOf(feature.getProperty("reclasse").getValue());
                if(reclasse.startsWith("4")){
                    pdense_bv += intersectArea;
                    urba_bv += intersectArea;
                }else if(reclasse.startsWith("5")){
                    dense_bv += intersectArea;
                    urba_bv += intersectArea;
                }else if(reclasse.startsWith("6")){
                    tdense_bv += intersectArea;
                    urba_bv += intersectArea;
                }
            }
        }
        pdense_bv = pdense_bv * 100.0 / area_bv;
        dense_bv  =  dense_bv * 100.0 / area_bv;
        tdense_bv = tdense_bv * 100.0 / area_bv;
        urba_bv   =   urba_bv * 100.0 / area_bv;


        /* =====================================================================
        bv_artif AS (
            SELECT
		bv.id_site,
		round((sum(tache_artif.area) * 100::double precision / bv.area_bv)::numeric, 2) AS artif_bv
            FROM referentiels_geo.tache_artif,bv
            WHERE st_intersects(bv.geom_bv, tache_artif.geom)
            GROUP BY bv.id_site, bv.area_bv
            ),
        */
        double artif_bv = 0;
        final FeatureCollection tacheArtif = georef.getFeatureCollection(GeoReferentials.TYPE_TACHE_ARTIF, geom_bv);
        try(FeatureIterator ite = tacheArtif.iterator()){
            while(ite.hasNext()) {
                artif_bv += ((Geometry) ite.next().getDefaultGeometryProperty().getValue()).intersection(geom_bv).getArea();
            }
        }
        artif_bv   =   artif_bv * 100.0 / area_bv;

        /* =====================================================================
        urb_site AS (
            SELECT
                sites.id_site,
                round((sum(st_area2d(st_intersection(tache_urbaine.geom, sites.geom_sitebuffer))) * 100::double precision / st_area2d(sites.geom_sitebuffer))::numeric, 2) AS urb,
                st_area2d(sites.geom_sitebuffer) AS surf_sitebuffer,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '4'::text
                    THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, sites.geom_sitebuffer))) * 100::double precision / st_area2d(sites.geom_sitebuffer))::numeric, 2)
                    ELSE NULL::numeric
                END AS pdense,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '5'::text
                    THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, sites.geom_sitebuffer))) * 100::double precision / st_area2d(sites.geom_sitebuffer))::numeric, 2)
                    ELSE NULL::numeric
                END AS dense,
                CASE
                    WHEN "left"(tache_urbaine.reclasse::text, 1) = '6'::text THEN round((sum(st_area2d(st_intersection(tache_urbaine.geom, sites.geom_sitebuffer))) * 100::double precision / st_area2d(sites.geom_sitebuffer))::numeric, 2)
                    ELSE NULL::numeric
                END AS tdense
            FROM referentiels_geo.tache_urbaine, expertise.sites
            WHERE st_intersects(tache_urbaine.geom, sites.geom_sitebuffer)
                AND "left"(tache_urbaine.reclasse::text, 1)::integer > 3
            GROUP BY sites.id_site, tache_urbaine.reclasse, sites.geom_sitebuffer
            ),
        */

        /* =====================================================================
        urb AS (
            SELECT
                urb_site.id_site,
                max(urb_site.pdense) AS pdense,
                max(urb_site.dense) AS dense,
                max(urb_site.tdense) AS tdense,
                sum(urb_site.urb) AS urba,
                urb_site.surf_sitebuffer
            FROM urb_site
            GROUP BY urb_site.id_site, urb_site.surf_sitebuffer
            ),
        */
        double pdense = 0;
        double dense = 0;
        double tdense = 0;
        double urba = 0;
        final FeatureCollection tacheUrbaineSite = georef.getFeatureCollection(GeoReferentials.TYPE_TACHE_URBAINE, siteGeomBuffer);
        try(FeatureIterator ite = tacheUrbaineSite.iterator()){
            while(ite.hasNext()){
                final Feature feature = ite.next();
                final Geometry geom = (Geometry) feature.getDefaultGeometryProperty().getValue();

                final double intersectArea = siteGeomBuffer.intersection(geom).getArea();

                final String reclasse = String.valueOf(feature.getProperty("reclasse").getValue());
                if(reclasse.startsWith("4")){
                    pdense += intersectArea;
                    urba += intersectArea;
                }else if(reclasse.startsWith("5")){
                    dense += intersectArea;
                    urba += intersectArea;
                }else if(reclasse.startsWith("6")){
                    tdense += intersectArea;
                    urba += intersectArea;
                }
            }
        }
        pdense = pdense * 100.0 / siteGeomBufferArea;
        dense  =  dense * 100.0 / siteGeomBufferArea;
        tdense = tdense * 100.0 / siteGeomBufferArea;
        urba   =   urba * 100.0 / siteGeomBufferArea;



        /* =====================================================================
        artif AS (
            SELECT
		sites.id_site,
		round(sum(st_area2d(st_intersection(sites.geom_sitebuffer, tache_artif.geom)) * 100::double precision / st_area2d(sites.geom_sitebuffer))::numeric, 2) AS artif
            FROM referentiels_geo.tache_artif, expertise.sites
            WHERE st_intersects(sites.geom_sitebuffer, tache_artif.geom)
            GROUP BY sites.id_site
            ),
        */
        double artif = 0;
        final FeatureCollection tacheArtifSite = georef.getFeatureCollection(GeoReferentials.TYPE_TACHE_ARTIF, siteGeomBuffer);
        try(FeatureIterator ite = tacheArtifSite.iterator()){
            while(ite.hasNext()){
                final Feature feature = ite.next();
                final Geometry geom = (Geometry) feature.getDefaultGeometryProperty().getValue();
                final double intersectArea = siteGeomBuffer.intersection(geom).getArea();
                artif += intersectArea;
            }
        }
        artif   =   artif * 100.0 / siteGeomBufferArea;

        /* =====================================================================
        SELECT
            bv_urb.id_site,                                                                                 --> id_site
            round(bv_urb.surf_site / 10000::numeric, 2) AS surf_site_ha,                                    --> id_site
            round((urb.surf_sitebuffer / 10000::double precision)::numeric, 2) AS surf_sitebuffer_ha,       --> id_site
            round((bv_urb.area_bv / 10000::double precision)::numeric, 2) AS surf_bv_ha,                    --> id_s
            artif.artif AS "I12_artif",                                                                     --> artif_site
            bv_artif.artif_bv AS "I12_artif_bv",                                                            --> artif_bv
            urb.pdense,                                                                                     --> pdense_site
            bv_urb.pdense_bv,                                                                               --> pdense_bv
            urb.dense,                                                                                      --> dense_site
            bv_urb.dense_bv,                                                                                --> dense_bv
            urb.tdense,                                                                                     --> tdense_site
            bv_urb.tdense_bv,                                                                               --> tdense_bv
            urb.urba,                                                                                       --> urba_site
            bv_urb.urba_bv                                                                                  --> urba_bv
        FROM urb,
            artif,
            bv_urb,
            bv_artif
        WHERE bv_urb.id_site = bv_artif.id_site
            AND bv_urb.id_site = artif.id_site
            AND bv_urb.id_site = urb.id_site
        GROUP BY artif.artif, bv_urb.id_site, bv_urb.surf_site, bv_urb.area_bv,
                bv_artif.artif_bv, urb.surf_sitebuffer, urb.pdense, urb.dense,
                urb.tdense, urb.urba, bv_urb.pdense_bv, bv_urb.dense_bv, bv_urb.tdense_bv, bv_urb.urba_bv;
        */

        indexes.add(indicator.artifSiteSpi  .createIndex(artif, year));
        indexes.add(indicator.artifBvSpi    .createIndex(artif_bv, year));
        indexes.add(indicator.pdenseSiteSpi .createIndex(pdense, year));
        indexes.add(indicator.pdenseBvSpi   .createIndex(pdense_bv, year));
        indexes.add(indicator.denseSiteSpi  .createIndex(dense, year));
        indexes.add(indicator.denseBvSpi    .createIndex(dense_bv, year));
        indexes.add(indicator.tdenseSiteSpi .createIndex(tdense, year));
        indexes.add(indicator.tdenseBvSpi   .createIndex(tdense_bv, year));
        indexes.add(indicator.urbaSiteSpi   .createIndex(urba, year));
        indexes.add(indicator.urbaBvSpi     .createIndex(urba_bv, year));
    }

}
