package eu.eudat.criteria.serialzier;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import eu.eudat.criteria.entities.Criteria;

import java.io.IOException;

public class CriteriaSerializer extends JsonDeserializer<Criteria<?>> implements ContextualDeserializer {

	private JavaType valueType;

	@Override
	public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
		JavaType wrapperType = property.getType();
		JavaType valueType = wrapperType.containedType(0);
		CriteriaSerializer deserializer = new CriteriaSerializer();
		deserializer.valueType = valueType;
		return deserializer;
	}

	@Override
	public Criteria<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
		ObjectCodec oc = jp.getCodec();
		JsonNode jsonNode = oc.readTree(jp);
		if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
			Criteria<?> criteria = new Criteria<>();
			criteria.setAs(jsonNode.asText());
			return criteria;
		} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
			ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<?>>() {
			});
			return reader.readValue(jsonNode);
		}
		return null;
	}
}
