/**
 *
 */
package org.gcube.portlets.user.gisviewer.server.datafeature;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.gcube.portlets.user.gisviewer.client.Constants;
import org.gcube.portlets.user.gisviewer.client.commons.beans.LayerItem;
import org.gcube.portlets.user.gisviewer.client.commons.beans.WebFeatureTable;
import org.gcube.portlets.user.gisviewer.server.datafeature.wfs.WFSExporter;
import org.gcube.portlets.user.gisviewer.server.datafeature.wfs.WFSExporter.WFS_TO;
import org.gcube.portlets.user.gisviewer.shared.CSVFile;
import org.gcube.portlets.user.gisviewer.shared.CSVRow;

import com.extjs.gxt.ui.client.data.BaseModel;


// TODO: Auto-generated Javadoc
/**
 * The Class FeatureParser.
 *
 * @author Ceras
 * updated by Francesco Mangiacrapa
 *         francesco.mangiacrapa@isti.cnr.it Jan 21, 2016
 *
 *         <wfs:FeatureCollection
 *         xmlns:aquamaps="http://www.aquamaps.org"
 *         xmlns:ogc="http://www.opengis.net/ogc"
 *         xmlns:gml="http://www.opengis.net/gml"
 *         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *         xmlns:xlink="http://www.w3.org/1999/xlink"
 *         xmlns:ows="http://www.opengis.net/ows"
 *         xmlns:wfs="http://www.opengis.net/wfs" numberOfFeatures="12"
 *         timeStamp="2012-04-20T18:17:40.319+02:00" xsi:schemaLocation=
 *         "http://www.aquamaps.org http://geoserver2.d4science.research-infrastructures.eu:80/geoserver/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typeName=aquamaps%3AdepthMean http://www.opengis.net/wfs http://geoserver2.d4science.research-infrastructures.eu:80/geoserver/schemas/wfs/1.1.0/wfs.xsd"
 *         > <gml:featureMembers> <aquamaps:depthMean gml:id="depthMean.168267">
 *         <aquamaps:csquarecode>7700:390:3</aquamaps:csquarecode>
 *         <aquamaps:the_geom> </aquamaps:the_geom>
 *         <aquamaps:DepthMean>2732.0</aquamaps:DepthMean> </aquamaps:depthMean>
 *         </gml:featureMembers>
 */
public class FeatureParser {

	private static Logger log = Logger.getLogger(FeatureParser.class);

	/**
	 * Gets the data results.
	 *
	 * @param layerItems the layer items
	 * @param bbox the bbox
	 * @param maxWFSFeature the max wfs feature
	 * @param gCubeSecurityToken the g cube security token
	 * @param dataMinerURL the data miner URL
	 * @param zoomLevel the zoom level
	 * @return the data results
	 */
	public static List<WebFeatureTable> getDataResults(List<LayerItem> layerItems, String bbox, int maxWFSFeature, String gCubeSecurityToken, String dataMinerURL, int zoomLevel) {
		List<WebFeatureTable> results = new ArrayList<WebFeatureTable>();

		if(maxWFSFeature<0) {
			maxWFSFeature = Constants.MAX_WFS_FEATURES;
		}

		//IF WFS IS AVAILABLE USE WFS REQUEST OTHERWHISE TRY TO USE WPS SERVICE
		for (LayerItem layerItem : layerItems){
			WebFeatureTable table = getTableFromJson(layerItem, bbox, maxWFSFeature);

			if(table.isError()){
				if(layerItem.getUUID()!=null) {
					results.add(FeatureWPSRequest.getTableFromWPSService(layerItem, bbox, maxWFSFeature, gCubeSecurityToken, dataMinerURL, zoomLevel));
				}else{
					results.add(table);
				}
			}else
				results.add(table);
		}
		return results;
	}

	/**
	 * Gets the table from json.
	 *
	 * @param layerItem the layer item
	 * @param bbox the bbox
	 * @param maxWFSFeature the max wfs feature
	 * @return the table from json
	 */
	@SuppressWarnings("unchecked")
	private static WebFeatureTable getTableFromJson(LayerItem layerItem, String bbox, int maxWFSFeature) {
		WFSExporter wfsExporter = new WFSExporter();
		CSVFile csvFile = wfsExporter.getTableFromJsonToExport(layerItem, bbox, maxWFSFeature, WFS_TO.VIEW);
		log.info("The csv file exported to return is: "+csvFile);
		WebFeatureTable table = toWebFeatureTable(csvFile, layerItem.getName());
		return table;
	}
	
	
	/**
	 * To web feature table.
	 *
	 * @param csvFile the csv file
	 * @param tableName the table name
	 * @return the web feature table
	 */
	public static WebFeatureTable toWebFeatureTable(CSVFile csvFile, String tableName) {
		log.debug("toWebFeatureTable called");
		WebFeatureTable table = new WebFeatureTable();
		table.setTitle(tableName);
		try {
			log.debug("Trying to convert to "+WebFeatureTable.class.getName()+" the csvFile with headers: "+csvFile.getHeaderRow());
			log.trace("Rows are: "+csvFile.getValueRows().size());
			List<String> headers = csvFile.getHeaderRow().getListValues();
			List<CSVRow> csvRows = csvFile.getValueRows();
			for (int i=0; i<csvRows.size(); i++) {
				BaseModel row = new BaseModel();
				CSVRow csvRow = csvRows.get(i);
				List<String> values = csvRow.getListValues();
				for (int j=0; j<values.size(); j++) {
					row.set(headers.get(j), values.get(j));
				}
				table.addRow(row);
			}
			log.debug("Returning table with column names: "+table.getColumnNames()+". They are: "+table.getColumnNames().size());
			log.debug("The table has "+table.getRows().size() + " rows");
		}catch (Exception e) {
			log.error("Error on trasforming the "+CSVFile.class.getSimpleName()+" to "+WebFeatureTable.class.getSimpleName(),e);
		}
		return table;
	}
	
}
