package estivate.core.eval.lang;

import org.jsoup.helper.StringUtil;
import org.jsoup.select.Elements;

import estivate.core.ast.QueryAST;
import estivate.core.ast.lang.SelectQueryAST;
import estivate.core.eval.EstivateEvaluator2.EvalContext;
import estivate.core.eval.EstivateEvaluator2.QueryEvaluator;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SelectQueryEvaluator implements QueryEvaluator {

	public static final SelectQueryEvaluator INSTANCE = new SelectQueryEvaluator();

	public void evalQuery(EvalContext context, QueryAST query) {
		if (query instanceof SelectQueryAST) {
			SelectQueryAST ast = (SelectQueryAST) query;

			Elements queryResult = context.getQueryResult();

			String queryString = ast.getQueryString();

			if (!StringUtil.isBlank(queryString)) {

				Elements select = context.getQueryResult().select(queryString);

				if (ast.isFirst()) {
					queryResult = new Elements(select.first());
				} else if (ast.isLast()) {
					queryResult = new Elements(select.last());
				} else if (ast.getIndex() > 0) {
					if (ast.getIndex() > select.size()) {
						log.warn("index (" + ast.getIndex() + ") is greater than select result size (" + select.size()
								+ "). Peeking the last.");
						queryResult = new Elements(select.last());
					} else {
						queryResult = new Elements(select.get(ast.getIndex() - 1));
					}
				} else if (ast.isUnique() && select.size() != 1) {
					throw new RuntimeException("No unique element after query");
				} else {
					queryResult = select;
				}

			}

			context.setQueryResult(queryResult);

		}

	}

}

@@ -804,16 +804,85 @@
 ing)) %7B%0D
+%0A%09%09%09    %0D%0A%09%09%09    log.debug(%22%3E eval Select Query %5B%7B%7D%5D%22, queryString);%0D
 %0A%0D%0A%09%09%09%09E
@@ -1638,16 +1638,91 @@
 %09%09%09%7D%0D%0A%0D%0A
+%09%09%09%09log.debug(%22%3C eval Select Query %5B%7B%7D%5D : %7B%7D%22, queryString, queryResult);%0D%0A
 %09%09%09%7D%0D%0A%0D%0A

add log trace