V1_21.java [src/java/d/soils] Revision:   Date:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package d.soils;

import c.GIS_DB;
import c.SqlGIS;
import com.vividsolutions.jts.geom.Geometry;
import csip.ModelDataService;
import csip.ServiceException;
import csip.annotations.*;
import static csip.annotations.State.DEPRECATED;
import csip.utils.JSONUtils;
import database.DBResources;
import static database.DBResources.CR_R2GIS_CONFIG_STRING;
import gisobjects.GISObject;
import gisobjects.GISObjectException;
import gisobjects.GISObjectFactory;
import gisobjects.db.GISEngine;
import static gisobjects.db.GISEngineFactory.createGISEngine;
import gisobjects.vector.GIS_FeatureCollection;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
import javax.ws.rs.*;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


/**
 * REST Web Service. Front end callable.
 *
 * @author wlloyd, od
 */
@Name("Soils")
@Description("IET soils")
@VersionInfo("1.2")
@State(DEPRECATED)
//@Path("d/soils/1.2")
@Deprecated
@Resource(from = DBResources.class)

public class V1_21 extends ModelDataService {

    static final String AOI = "AoI";
    protected GISObject inputGeometry;

    protected JSONArray outputObj;
    protected JSONObject aoa_input_geometry;
    protected Geometry aoa_geometry;

    @Override
    protected void preProcess() throws ServiceException {
        Map<String, JSONObject> inputParams = getParamMap();
        aoa_input_geometry = inputParams.get("AoI");
        if (null == aoa_input_geometry) {
            throw new ServiceException("No 'AoI' item was found in the JSON input.  Please specify an 'AoI' .");
        }
    }

    @Override
    protected void doProcess() throws Exception {
        try (Connection conn = resources().getJDBC(CR_R2GIS_CONFIG_STRING); GIS_DB db = new SqlGIS(conn); GISEngine gisEngine = createGISEngine(conn)) {
            //  For each feature in the feature collection do ??  Or just one??  Multiple AoI's ??  
            //  [Original code made it look like the above was possible, but it never actually did more than one feature or more than one AoI
            //  So, new code is just doing the first feature of the first AoI specified.
            

            outputObj = new JSONArray(getParam().toString());
            JSONArray aPoly = new JSONArray();
            JSONArray aCoord = new JSONArray();
            JSONObject featureColl = parameter().getJSON(AOI);
            GISObjectFactory.setFixBadGeometries(true);
            inputGeometry = GISObjectFactory.createGISObject(featureColl, gisEngine);
            GISObject geometry = getFirstGeometry(inputGeometry);
            geometry.makeValid(GISObject.UsePurpose.sql_server_use, GISObject.GISType.all_types);
            String geoWKT = geometry.toWKT();

            Collection<GIS_DB.Soil> soils = db.findSoilsForPolygonWithSand(geoWKT, 0.0);
            Collection<GIS_DB.Soil> soilsW = db.findSoilsForPolygonWeps(geoWKT, 0.0);
            
            
            for (GIS_DB.Soil soilObj : soils) {
                LOG.log(Level.INFO, "\n\n\n\n\n\n\n\n\nSAND TOTAL VALUE=" + soilObj.sandtotalR);

                JSONArray aSoil = new JSONArray();
                aSoil.put(JSONUtils.data("ssurgo_cokey", soilObj.coKey));
                aSoil.put(JSONUtils.data("ssurgo_mukey", soilObj.muKey));
                aSoil.put(JSONUtils.data("ssurgo_areasymbol", soilObj.coFips));
                aSoil.put(JSONUtils.data("ssurgo_compname", soilObj.compName));
                aSoil.put(JSONUtils.data("ssurgo_kffact", soilObj.kffact));
                aSoil.put(JSONUtils.data("ssurgo_tfact", soilObj.tfact, soilObj.tfactUnits));
                aSoil.put(JSONUtils.data("ssurgo_muname", soilObj.muName));
                aSoil.put(JSONUtils.data("ssurgo_musym", soilObj.muSym));
                aSoil.put(JSONUtils.data("per_water", soilObj.perWater, soilObj.perWaterUnits));
                aSoil.put(JSONUtils.data("per_wind", soilObj.perWind, soilObj.perWindUnits));
                aSoil.put(JSONUtils.data("r2_r2name", soilObj.r2Name));
                aSoil.put(JSONUtils.data("r2_r2path", soilObj.r2Path));
                aSoil.put(JSONUtils.data("length_r", soilObj.lengthR, soilObj.lengthRUnits));
                aSoil.put(JSONUtils.data("ssurgo_slopeR", soilObj.slopeR, soilObj.slopeRUnits));
                aSoil.put(JSONUtils.data("ssurgo_sandtotalR", soilObj.sandtotalR, soilObj.sandtotalRUnits));
                aSoil.put(JSONUtils.data("percent_of_aoi", soilObj.percentAoi, soilObj.percentAoiUnits));
                aSoil.put(JSONUtils.data("acres_in_aoi", soilObj.sizeAoi, soilObj.sizeAoiUnits));
                aPoly.put(aSoil);
            }

            for (GIS_DB.Soil soilObj : soilsW) {
                
                JSONArray aSoil = new JSONArray();
                aSoil.put(JSONUtils.data("ssurgo_cokey", soilObj.coKey));
                aSoil.put(JSONUtils.data("ssurgo_mukey", soilObj.muKey));
                aSoil.put(JSONUtils.data("ssurgo_areasymbol", soilObj.coFips));
                aSoil.put(JSONUtils.data("ssurgo_compname", soilObj.compName));
                aSoil.put(JSONUtils.data("ssurgo_kffact", soilObj.kffact));
                aSoil.put(JSONUtils.data("ssurgo_tfact", soilObj.tfact, soilObj.tfactUnits));
                aSoil.put(JSONUtils.data("ssurgo_muname", soilObj.muName));
                aSoil.put(JSONUtils.data("ssurgo_musym", soilObj.muSym));
                aSoil.put(JSONUtils.data("per_water", soilObj.perWater, soilObj.perWaterUnits));
                aSoil.put(JSONUtils.data("per_wind", soilObj.perWind, soilObj.perWindUnits));
                aSoil.put(JSONUtils.data("weps_name", soilObj.wepsName));
                aSoil.put(JSONUtils.data("weps_path", soilObj.wepsPath));
                aSoil.put(JSONUtils.data("length_r", soilObj.lengthR, soilObj.lengthRUnits));
                aSoil.put(JSONUtils.data("ssurgo_slopeR", soilObj.slopeR, soilObj.slopeRUnits));

                aSoil.put(JSONUtils.data("percent_of_aoi", soilObj.percentAoi, soilObj.percentAoiUnits));
                aSoil.put(JSONUtils.data("acres_in_aoi", soilObj.sizeAoi, soilObj.sizeAoiUnits));
                // Check if soil is already in aPoly - if so add weps path/name otherwise append
                addWepsSoil(aPoly, aSoil, soilObj);
            }
            aCoord.put(aPoly);

            outputObj.put(aCoord);
        } 
    }

    @Override
    protected void postProcess() throws Exception {
       //results().(outputObj);
    }

    protected GISObject getFirstGeometry(GISObject inputGeo) throws ServiceException {
        GISObject ret_val = null;
        if (null != inputGeo) {
            switch (inputGeo.getType()) {
                case featurecollection:
                    int fCount = ((GIS_FeatureCollection) inputGeo).getFeatureCount();
                    if (fCount <= 0) {
                        throw new ServiceException("Invalid geoemtry type used in the AoI input param.  FeatureCollection has no feature geometries.");
                    }
                     {
                        try {
                            ret_val = ((GIS_FeatureCollection) inputGeo).getGeometry(0);
                        } catch (GISObjectException ex) {
                            throw new ServiceException("\"Invalid geoemtry type used in the AoI input param: " + ex.getMessage(), ex);
                        }
                    }
                    break;

                case geometrycollection:
                case polygon:
                case multipolygon:
                    ret_val = inputGeo;
                    break;

                default:
                    throw new ServiceException("Invalid geoemtry type used in the AoI input param.");
            }
        }

        return ret_val;
    }

    protected void addWepsSoil(JSONArray aPolygon, JSONArray wepsSoil, GIS_DB.Soil soilObj) throws JSONException {
        String wepsCokey = JSONUtils.getValueByKey(wepsSoil, "ssurgo_cokey");
        String wepsaoi = JSONUtils.getValueByKey(wepsSoil, "acres_in_aoi");
        for (int i = 0; i < aPolygon.length(); i++) {
            JSONArray aSoil = aPolygon.getJSONArray(i);
            String cokey = JSONUtils.getValueByKey(aSoil, "ssurgo_cokey");
            String aoi = JSONUtils.getValueByKey(aSoil, "acres_in_aoi");
            if ((cokey.equals(wepsCokey)) && (aoi.equals(wepsaoi))) {
                // append weps attrs to existing soil
                aSoil.put(JSONUtils.data("weps_name", soilObj.wepsName));
                aSoil.put(JSONUtils.data("weps_path", soilObj.wepsPath));
                return;
            }
        }
        // add new WEPS soil results because its not there
        aPolygon.put(wepsSoil);
    }

}