package eu.eudat.criteria;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import eu.eudat.criteria.entities.Criteria;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.query.UserQuery;

import java.io.IOException;
import java.util.*;

public class UserCriteria {
	private Criteria<UUID> id;
	private Criteria<String> email;

	public Criteria<UUID> getId() {
		return id;
	}

	public void setId(JsonNode jsonNode) throws IOException {
		if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
			Criteria<UUID> criteria = new Criteria<>();
			criteria.setAs(jsonNode.asText());
			this.id = criteria;
		} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
			ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<UUID>>() {
			});
			this.id = reader.readValue(jsonNode);
		}
	}

	public Criteria<String> getEmail() {
		return email;
	}

	public void setEmail(JsonNode jsonNode) throws IOException {
		if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
			Criteria<String> criteria = new Criteria<>();
			criteria.setAs(jsonNode.asText());
			this.email = criteria;
		} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
			ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<String>>() {
			});
			this.email = reader.readValue(jsonNode);
		}
	}

	protected List<String> buildFields(String path) {
		Set<String> fields = new LinkedHashSet<>();
		path = path != null && !path.isEmpty() ? path + "." : "";
		if (this.id != null) fields.add(path + this.id.getAs());
		if (this.email != null) fields.add(path + this.email.getAs());
		if (!fields.contains(path + "id")) fields.add(path + "id");
		return new LinkedList<>(fields);
	}

	public UserQuery buildQuery(DatabaseRepository dao) {
		List<String> fields = this.buildFields("");
		UserQuery query = new UserQuery(dao.getUserInfoDao(), fields);
		if (this.id != null) query.setId(this.id.getValue());
		return query;
	}
}
