/**
 *
 */
package fr.visian.vip.client.sdk.request.extract;

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

import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;

import fr.visian.vip.client.sdk.exception.CreateModelException;
import fr.visian.vip.client.sdk.model.Sensor;
import fr.visian.vip.client.sdk.model.factory.SensorFactory;
import lombok.extern.log4j.Log4j2;

/**
 * Extract sensors from a response.
 *
 * @author Bertrand
 *
 */
@Log4j2
public class SensorExtract extends ResponseExtract
{
	/** The {@link SensorFactory}. */
	private final SensorFactory factory = new SensorFactory();

	/*
	 * (non-Javadoc)
	 * @see fr.visian.vip.client.sdk.request.extract.ResponseExtract#getLog()
	 */
	@Override
	protected Logger getLog()
	{
		return (log);
	}

	/**
	 * Extract sensors from a request's response.
	 *
	 * @param response
	 *            The server's response.
	 * @return The list of sensors from the JSON.
	 * @throws JSONException
	 *             If JSON cannot be parsed.
	 * @throws CreateModelException
	 *             If data in the JSON are not valid.
	 */
	public List<Sensor> extractSensors(final HttpResponse<JsonNode> response) throws JSONException, CreateModelException
	{
		final List<Sensor> sensors = new ArrayList<Sensor>();
		final JSONArray array = response.getBody().getArray();
		for (int i = 0; i < array.length(); i++)
		{
			final Sensor s = this.factory.createSensorFromJSON(array.getJSONObject(i));
			sensors.add(s);
		}
		log.debug("Sensors received: " + sensors.size() + ".");
		return (sensors);
	}

	/**
	 * Extract a sensor from a request's response.
	 *
	 * @param response
	 *            The server's response.
	 * @return The {@link Sensor}.
	 * @throws CreateModelException
	 *             If data in the JSON are not valid.
	 */
	public Sensor extractSensor(final HttpResponse<JsonNode> response) throws CreateModelException
	{
		final Sensor s = this.factory.createSensorFromJSON(response.getBody().getObject());
		log.debug("Sensor received: " + s.toString() + ".");
		return (s);
	}
}