package ervu_business_metrics.deserializer;

import java.io.IOException;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import ervu_business_metrics.model.ReferenceEntity;

/**
 * @author Adel Kalimullin
 */
public class ReferenceEntityDeserializer extends JsonDeserializer<ReferenceEntity> {

  @Override
  public ReferenceEntity deserialize(JsonParser jsonParser,
      DeserializationContext deserializationContext) throws IOException, JacksonException {
    JsonNode node = jsonParser.readValueAsTree();

    if (node.isTextual()) {
      return new ReferenceEntity(node.asText());
    }
    else if (node.isObject()) {
      JsonNode idNode = node.get("id");
      if (idNode != null && idNode.isTextual()) {
        return new ReferenceEntity(idNode.asText());
      }
    }

    return null;
  }
}
