package eu.eudat.logic.utilities.json;

import com.fasterxml.jackson.databind.JsonNode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class JsonSearcher {

	public static List<JsonNode> findNodes(JsonNode root, String key, String value) {
		return findNodes(root, key, value, false);
	}

	public static List<JsonNode> findNodes(JsonNode root, String key, String value, boolean parent) {
		List<JsonNode> nodes = new ArrayList<>();
		for (Iterator<JsonNode> it = root.elements(); it.hasNext(); ) {
			JsonNode node = it.next();
			int found = 0;
			for (Iterator<String> iter = node.fieldNames(); iter.hasNext(); ) {
				String fieldName = iter.next();
				if (fieldName.equals(key)) {
					if (node.get(fieldName).asText().equals(value) || node.get(fieldName).asText().startsWith(value)) {
						if (parent) {
							nodes.add(root);
						} else {
							nodes.add(node);
						}
						found++;
					}
				}

			}
			if (found == 0) {
				nodes.addAll(findNodes(node, key, value, parent));
			}
		}
		return nodes;
	}

	public static List<String> getParentValues(JsonNode root, String childValue, String key) {
		List<String> values = new LinkedList<>();

		for (Iterator<JsonNode> it = root.elements(); it.hasNext(); ) {
			JsonNode node = it.next();
			int found = 0;
			for (Iterator<String> iter = node.fieldNames(); iter.hasNext(); ) {
				String fieldName = iter.next();
				if (fieldName.equals(key)) {
					if (node.get(fieldName).asText().equals(childValue) || node.get(fieldName).asText().startsWith(childValue)) {
						values.add(childValue);
						found++;
					}
				}

			}
			if (found == 0) {
				values.addAll(getParentValues(node, childValue, key));
				if (!values.isEmpty() && node.has(key)) {
					values.add(node.get(key).asText());
					values.remove(childValue);
				}
			}
		}

		return values;
	}
}
