V2_0.java [src/java/m/wqm/wqm06_scsednutsrp] Revision:   Date:
package m.wqm.wqm06_scsednutsrp;

import csip.ModelDataService;
import static csip.ModelDataService.KEY_DESC;
import static csip.ModelDataService.KEY_NAME;
import static csip.ModelDataService.KEY_VALUE;
import csip.api.server.PayloadResults;
import csip.api.server.ServiceException;
import csip.utils.JSONUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Path;
import csip.annotations.Description;
import csip.annotations.Name;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import soils.SoilsData;
import soils.db.tables.TableComponent;
import soils.db.tables.TableComponentCalculations;
import soils.db.tables.TableMapUnit;

/**
 *
 * @author Shaun Case
 */
@Name("WQM-06: Sediment and Nutrient Soil Runoff Potential (SedNutSRP)")
@Description("This service computes sediment and nutrient soil runoff potential for soil components in an area of analysis, and then compute soil runoff potential representing the area of analysis. The service primarily will consume data from the WQM-2 soil attributes service to compute soil runoff potential values for subsequent use by WQM-13 to compute threshold treatment level scores.")
@Path("m/scsednut_srp/2.0")
public class V2_0 extends ModelDataService {

  private V2_0.AoA aoa;

  @Override
  protected void preProcess() throws ServiceException {
    V2_0.AoA.setRequiredInputs(new ArrayList<>(Arrays.asList(AoA.AOA_ID, AoA.MAP_UNIT_LIST)),
        new ArrayList<>(Arrays.asList(TableMapUnit.MUKEY, SoilsData.MAPUNIT_COMPONENT_LIST_NAME)),
        new ArrayList<>(Arrays.asList(TableComponent.COKEY, TableComponent.TAXORDER_NAME, TableComponent.SLOPE_R_NAME,
            TableComponent.HYDGRP_NAME, SoilsData.MAPUNIT_COMPONENT_LIST_NAME,
            TableComponentCalculations.COMP_AREA_NAME, TableComponentCalculations.COARSE_FRAG_NAME,
            TableComponentCalculations.KFFACT_NAME, TableComponentCalculations.WTBL_TOP_MIN_NAME,
            TableComponentCalculations.HWT_LT_24_NAME, TableComponentCalculations.WTBL_NAME)),
        null);
  }

  @Override
  protected void doProcess() throws ServiceException, JSONException {
    aoa = new V2_0.AoA(JSONUtils.preprocess(getParam()));
    aoa.computeComponentSedNutSRP(aoa.isDrained());
    aoa.computeAoASRP();
  }

  @Override
  protected void postProcess() throws Exception {
    JSONArray tArray = aoa.toJSON();
    for (int i = 0; i < tArray.length(); i++) {
      JSONObject outObject = tArray.getJSONObject(i);
      if (outObject.optString(KEY_NAME, "").equalsIgnoreCase(soils.AoA.MAP_UNIT_LIST)) {
        JSONArray outArray2 = outObject.getJSONArray(KEY_VALUE);
        results().put(soils.AoA.MAP_UNIT_LIST, outArray2);
      } else {
        writeResults(results(), outObject);
      }
    }

  }

  protected void writeResults(PayloadResults results, JSONObject outObject) throws Exception {
    results.put(outObject.getString(KEY_NAME), outObject.getString(KEY_VALUE), outObject.getString(KEY_DESC));
  }

  /**
   *
   */
  public class AoA extends soils.AoA {

    /**
     *
     * @param inputData
     * @throws ServiceException
     * @throws JSONException
     */
    public AoA(Map<String, JSONObject> inputData) throws ServiceException, JSONException {
      super(inputData);
    }

    /**
     *
     * @throws JSONException
     */
    public JSONArray toJSON() throws JSONException {
      JSONArray outArray = new JSONArray();

      tableAoA.setOutputColumns(new ArrayList<>(Arrays.asList(AoA.AOA_ID, AoA.SRP)));
            try {
      setMapUnitOutputColumns(new ArrayList<>(Arrays.asList(TableMapUnit.MUKEY)),
          new ArrayList<>(Arrays.asList(TableComponent.COKEY, TableComponentCalculations.SRP_NAME)));
            } catch (ServiceException ex) {
                throw new JSONException("Cannot format JSON Results: " + ex.getMessage());
            }

      toJSON(true, outArray);
      return outArray;
//            //Using put result here because need access to "res" in ModelDataServices.  [Perhaps results() should be protected and not private?]
//            //  Because the TableColumn class handles all the specifics of how to format information, and if units, descriptions, etc., were required
//            //  for the output JSON, it is all contained and abstracted to avoid confusion for programmers writing simple services.  Thus,
//            //  direct access to the ModelDataServices.res member would be hugely benefitial here...
//            for (int i = 0; i < outArray.length(); i++) {
//                results().put(outArray.getJSONObject(i));
//            }
    }
  }

  /* Required inputs
                        JSONUtils.getStringParam(group, "cokey", "err"),
                        JSONUtils.getDoubleParam(group, "aoa_comp_area", 0),
                        JSONUtils.getStringParam(group, "aoa_comp_hsg", "err"),
                        JSONUtils.getStringParam(group, "aoa_comp_taxorder", "err"),
                        JSONUtils.getDoubleParam(group, "aoa_comp_kfact", 0),
                        JSONUtils.getDoubleParam(group, "aoa_comp_slope", 0),
                        JSONUtils.getDoubleParam(group, "aoa_comp_coarse_frag", 0),
                        JSONUtils.getBooleanParam(group, "aoa_comp_drained", false),
                        JSONUtils.getStringParam(group, "aoa_comp_wtbl", "err"),
                        JSONUtils.getBooleanParam(group, "aoa_comp_hwt_lt_24", false));
   */
}