package ru.yandex.autodoc.common.doc.view.handlers;

import ru.yandex.autodoc.common.doc.MethodsDocumentationBuilder;
import ru.yandex.autodoc.common.doc.abstracts.MethodDocumentation;
import ru.yandex.autodoc.common.doc.view.Markup;
import ru.yandex.autodoc.common.doc.view.common.MarkupRequestHandler;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author avhaliullin
 */
@Deprecated
public class MethodDocumentationHandler implements MarkupRequestHandler {
    private MethodDocumentationMarkuper methodDocumentationMarkuper;
    private MethodsDocumentationBuilder methodsDocumentationBuilder;

    public MethodDocumentationHandler(MethodDocumentationMarkuper methodDocumentationMarkuper,
                                      MethodsDocumentationBuilder methodsDocumentationBuilder) {
        this.methodDocumentationMarkuper = methodDocumentationMarkuper;
        this.methodsDocumentationBuilder = methodsDocumentationBuilder;
    }

    @Override
    public Markup handle(Map<String, String> params) {
        String others = "Others";
        List<MethodDocumentation> methods = methodsDocumentationBuilder.getDocumentation();
        Map<String, List<MethodDocumentation>> category2Methods = methods.stream()
                .collect(Collectors.groupingBy(m -> m.getCategory() == null ? others : m.getCategory()));

        List<String> categories = category2Methods.keySet().stream().sorted((x, y) -> {
            if (Objects.equals(x, others)) {
                return Objects.equals(y, others) ? 0 : 1;
            }
            if (Objects.equals(y, others)) {
                return -1;
            }
            return x.compareTo(y);
        }).collect(Collectors.toList());
        return categories.stream().map(c -> {
            String id = "category-" + c;
            Markup content = category2Methods.get(c).stream().map(m ->
                    (Markup) new Markup.Section(m.getName(), "Метод " + m.getName(),
                            methodDocumentationMarkuper.toMarkup(m))
            ).reduce(Markup.EMPTY, Markup::concat);
            return (Markup) new Markup.Section(id, c, content);
        }).reduce(Markup.EMPTY, Markup::concat);
    }
}
