package ru.yandex.webmaster3.core.searchquery;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import org.apache.commons.lang3.StringUtils;

/**
 * @author aherman
 */
public class QueryUtils {

    public static final Function<Double, Double> FORMAT_PERCENT = value -> value == null ? null : value * 100.0D;

    // Inspired by arc/arcadia/kernel/search_query/search_query.cpp
    public static String CheckAndFixQueryStringUTF8(String query) {
        if (StringUtils.isEmpty(query)) {
            return StringUtils.EMPTY;
        }
        StringBuilder sb = new StringBuilder(query.length());
        boolean wasSpace = false;
        boolean start = true;
        for (int i = 0; i < query.length(); i++) {
            char c = query.charAt(i);
            if (c <= 32 || c == 0x7F) {
                wasSpace = true;
            } else {
                if (wasSpace) {
                    if (!start) {
                        sb.append(' ');
                    }
                    wasSpace = false;
                }
                start = false;
                sb.append(c);
            }
        }
        return sb.toString().toLowerCase();
    }

    public static List<String> CheckAndFixQueryStringUTF8(Collection<String> queries) {
        if (queries == null || queries.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> result = new ArrayList<>(queries.size());
        for (String query : queries) {
            String q = CheckAndFixQueryStringUTF8(query);
            if (!StringUtils.isEmpty(q)) {
                result.add(q);
            }
        }
        return result;
    }

    public static List<String> CheckAndFixQueryStringUTF8(String[] queries) {
        if (queries == null || queries.length == 0) {
            return Collections.emptyList();
        }
        return CheckAndFixQueryStringUTF8(Arrays.asList(queries));
    }
}
