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

import ru.yandex.autodoc.common.doc.error.ErrorDescription;
import ru.yandex.autodoc.common.doc.error.ErrorsBlockInfo;
import ru.yandex.autodoc.common.doc.view.Markup;

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

/**
 * @author avhaliullin
 */
public class ErrorsDocumentationMarkuper {
    private final ObjectFormatResolver objectFormatResolver;

    public ErrorsDocumentationMarkuper(ObjectFormatResolver objectFormatResolver) {
        this.objectFormatResolver = objectFormatResolver;
    }

    public Markup toMarkup(List<ErrorsBlockInfo> blocks) {
        return new Markup.Group(
                blocks.stream().map(block -> {
                    String title = block.name;
                    if (block.description != null) {
                        title += " - " + block.description;
                    }
                    return new Markup.Section(block.name, title, errorListToMarkup(block.errors));
                }).collect(Collectors.toList())
        );
    }

    public Markup errorListToMarkup(List<ErrorDescription> errors) {
        return new Markup.UL(
                errors.stream().map(error -> {
                    if (error.description == null && error.jsonExample == null) {
                        return new Markup.Block(new Markup.Text(error.problem));
                    } else {
                        Markup content = error.description == null
                                ? Markup.EMPTY
                                : new Markup.Block(new Markup.Text(error.description));
                        if (error.jsonExample != null) {
                            content = content.concat(new Markup.DocumentedJson(error.jsonExample));
                        } else if (error.model != null) {
                            content = content.concat(objectFormatResolver.resolve(error.model));
                        }
                        return new Markup.Block(new Markup.Spoiler(
                                error.problem,
                                content
                        ));
                    }
                }).collect(Collectors.toList())
        );
    }
}
