package ru.yandex.webmaster3.admin.http.request;

import ru.yandex.autodoc.common.doc.types.ValueType;
import ru.yandex.webmaster3.core.http.ParameterConverter;
import ru.yandex.webmaster3.storage.util.yt.YtPath;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author avhaliullin
 */
public class YtPathConverter implements ParameterConverter {
    private static final Pattern UI_URL_PATTERN = Pattern.compile("^https://yt.yandex-team.ru/([a-zA-Z]+)/#(.+)$");
    private static final Set<String> KNOWN_CLUSTERS = new HashSet<>(Arrays.asList("arnold", "hahn"));
    private static final String PATH_PARAM_PREFIX = "path=";

    @Override
    public Object convert(String value, Type toType) {
        if (toType.equals(YtPath.class)) {
            YtPath result = parseFromUrl(value);
            if (result == null) {
                result = YtPath.fromString(value);
            }
            if (result != null && !KNOWN_CLUSTERS.contains(result.getCluster())) {
                throw new IllegalArgumentException("Unknown cluster " + result.getCluster());
            }
            return result;
        }
        return null;
    }

    private static YtPath parseFromUrl(String url) {
        Matcher m = UI_URL_PATTERN.matcher(url);
        if (m.find()) {
            String cluster = m.group(1);
            String query = m.group(2);
            String[] parts = query.split("&");
            for (String paramValue : parts) {
                if (paramValue.startsWith(PATH_PARAM_PREFIX)) {
                    try {
                        return YtPath.create(cluster, paramValue.substring(PATH_PARAM_PREFIX.length()));
                    } catch (IllegalArgumentException e) {
                        return null;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public ValueType describeType(Type type) {
        return new ValueType.Primitive("YT path", ValueType.STRING, "arnold://some/table");
    }
}
