package edu.hm.hafner.analysis.parser;

import java.io.Serial;
import java.util.Optional;
import java.util.regex.Matcher;

import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.LookaheadParser;
import edu.hm.hafner.analysis.Severity;
import edu.hm.hafner.util.LookaheadStream;

import static edu.hm.hafner.analysis.Categories.*;

/**
 * A parser for the Sphinx warnings generated by the linkcheck builder.
 *
 * @author Davide Mancusi
 */
public class SphinxBuildLinkCheckParser extends LookaheadParser {
    @Serial
    private static final long serialVersionUID = 1L;

    private static final String SPHINX_BUILD_LINK_CHECK_WARNING_PATTERN = "^(.*):(\\d+|None|): \\[(.*?)\\] (.*)";

    /**
     * Creates a new instance of {@link SphinxBuildLinkCheckParser}.
     */
    public SphinxBuildLinkCheckParser() {
        super(SPHINX_BUILD_LINK_CHECK_WARNING_PATTERN);
    }

    @Override
    protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStream lookahead,
            final IssueBuilder builder) {
        var message = matcher.group(4);
        var category = guessCategoryIfEmpty(matcher.group(3), message);

        return builder.setFileName(matcher.group(1))
                .setLineStart(matcher.group(2))
                .setCategory(category)
                .setMessage(message)
                .setSeverity(mapPriority(category))
                .buildOptional();
    }

    private Severity mapPriority(final String priority) {
        if (equalsIgnoreCase(priority, "broken")) {
            return Severity.WARNING_HIGH;
        }
        else {
            return Severity.WARNING_NORMAL;
        }
    }
}
