package semantic.model;

import java.util.List;
import java.util.Optional;

public class DoItYourselfModel implements IModelFunctions {
	IConvenienceInterface model;

	public DoItYourselfModel(IConvenienceInterface m) {
		this.model = m;
	}

	@Override
	public String createPlace(String name) {
		String placeURI = model.getEntityURI("Place").get(0);
		return model.createInstance(name, placeURI);
	}

	@Override
	public String createInstant(TimestampEntity instant) {
		String instantURI = model.getEntityURI("Instant").get(0);
		String propertyURI = model.getEntityURI("a pour timestamp").get(0);
		String instantInstanceURI = model.createInstance(instant.getTimeStamp(), instantURI);
		model.addDataPropertyToIndividual(instantInstanceURI, propertyURI, instant.getTimeStamp());
		return instantInstanceURI;
	}

	@Override
	public String getInstantTimestamp(String instantURI) {
		String propertyURI = model.getEntityURI("a pour timestamp").get(0);
		List<List<String>> listProperties = model.listProperties(instantURI);
		Optional<List<String>> timestampProperty = listProperties.stream().filter(property ->
				property.get(0).equals(propertyURI)
		).findFirst();
		return timestampProperty.map(strings -> strings.get(1)).orElse(null);
	}

	@Override
	public String getInstantURI(TimestampEntity instant) {
		String instantTypeURI = model.getEntityURI("Instant").get(0);
		String propertyURI = model.getEntityURI("a pour timestamp").get(0);
		List<String> instancesURIList = model.getInstancesURI(instantTypeURI);
		Optional<String> instantURI = instancesURIList.stream().filter(instanceURI ->
				model.hasDataPropertyValue(
						instanceURI, propertyURI, instant.getTimeStamp())
		).findFirst();
		return instantURI.orElse(null);
	}

	@Override
	public String createObs(String value, String paramURI, String instantURI) {
		String obsClassURI = model.getEntityURI("Observation").get(0);
		String obsInstanceURI = model.createInstance(instantURI + "_" + paramURI + "_" + value, obsClassURI);
		String dataValueURI = model.getEntityURI("a pour valeur").get(0);
		String datePropertyURI = model.getEntityURI("a pour date").get(0);
		String sensorURI = model.whichSensorDidIt(getInstantTimestamp(instantURI), paramURI);
		model.addDataPropertyToIndividual(obsInstanceURI, dataValueURI, value);
		model.addObjectPropertyToIndividual(obsInstanceURI, datePropertyURI, instantURI);
		model.addObservationToSensor(obsInstanceURI, sensorURI);
		return obsInstanceURI;
	}
}
