package eu.dnetlib.broker.openaire;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.search.MatchQueryParser.ZeroTermsQuery;

import eu.dnetlib.broker.common.utils.DateParser;

public class ElasticSearchQueryUtils {

	public static void addMapConditionForTrust(final BoolQueryBuilder mapQuery, final String field, final Range trust) {
		final double min = NumberUtils.toDouble(trust.getMin(), 0);
		final double max = NumberUtils.toDouble(trust.getMax(), 1);
		mapQuery.must(QueryBuilders.rangeQuery(field).from(min).to(max));
	}

	public static void addMapCondition(final BoolQueryBuilder mapQuery, final String field, final String value) {
		if (StringUtils.isNotBlank(value)) {
			mapQuery.must(QueryBuilders.matchQuery(field, value).operator(Operator.AND).zeroTermsQuery(ZeroTermsQuery.ALL));
		}
	}

	public static void addMapCondition(final BoolQueryBuilder mapQuery, final String field, final List<String> list) {
		if (list != null && list.size() > 0) {
			final BoolQueryBuilder listQuery = QueryBuilders.boolQuery();
			for (final String s : list) {
				listQuery.should(QueryBuilders.matchQuery(field, s).operator(Operator.AND).zeroTermsQuery(ZeroTermsQuery.ALL));
			}
			mapQuery.must(listQuery);
		}
	}

	public static void addMapConditionForDates(final BoolQueryBuilder mapQuery, final String field, final List<Range> list) {
		if (list != null && list.size() > 0) {
			final BoolQueryBuilder listQuery = QueryBuilders.boolQuery();
			for (final Range range : list) {
				final long min = calculateTime(range.getMin(), 0);
				final long max = calculateTime(range.getMax(), Long.MAX_VALUE);

				listQuery.should(QueryBuilders.rangeQuery(field).from(min).to(max));
			}
			mapQuery.must(listQuery);
		}
	}

	public static long calculateTime(final String s, final long defaultValue) {
		final Date date = DateParser.parse(s);
		return date != null ? date.getTime() : defaultValue;
	}
}
