package edu.hm.hafner.analysis.parser;

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;

/**
 * A parser for the clang-tidy static analysis warnings parsed by Codechecker.
 *
 * Codechecker parses the *.plist files and converts it into plain text file.
 *
 * Better for human readers and for using grep and diff
 * It also puts the human-readable Severity at the start of a line.
 *
 */
public class CodeCheckerParser extends LookaheadParser {
    private static final long serialVersionUID = -3015592762345283582L;
    private static final String CODE_CHECKER_DEFECT_PATTERN =
            "^\\[(CRITICAL|HIGH|MEDIUM|LOW)\\] (.+):(\\d+):(\\d+): (.*?) \\[([^\\s]*?)\\]$";

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

    @Override
    protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStream lookahead,
            final IssueBuilder builder) {
        Severity priority;
        if (matcher.group(1).contains("CRITICAL")) {
            priority = Severity.ERROR;
        }
        else if (matcher.group(1).contains("HIGH")) {
            priority = Severity.WARNING_HIGH;
        }
        else if (matcher.group(1).contains("MEDIUM")) {
            priority = Severity.WARNING_NORMAL;
        }
        else {
            priority = Severity.WARNING_LOW;
        }
        return builder.setFileName(matcher.group(2))
                .setSeverity(priority)
                .setLineStart(matcher.group(3))
                .setColumnStart(matcher.group(4))
                .setCategory(matcher.group(6))
                .setMessage(matcher.group(5))
                .buildOptional();
    }
}

@@ -813,16 +813,27 @@
   %22%5E%5C%5C%5B(
+?%3Cseverity%3E
 CRITICAL
@@ -858,37 +858,81 @@
 %5C%5D (
-.+):(%5C%5Cd+):(%5C%5Cd+): (.*?) %5C%5C%5B(
+?%3Cpath%3E.+):(?%3Cline%3E%5C%5Cd+):(?%3Ccolumn%3E%5C%5Cd+): (?%3Cmessage%3E.*?) %5C%5C%5B(?%3Ccategory%3E
 %5B%5E%5C%5C
@@ -1303,33 +1303,42 @@
  (matcher.group(
-1
+%22severity%22
 ).contains(%22CRIT
@@ -1419,33 +1419,42 @@
  (matcher.group(
-1
+%22severity%22
 ).contains(%22HIGH
@@ -1546,17 +1546,26 @@
 r.group(
-1
+%22severity%22
 ).contai
@@ -1757,17 +1757,22 @@
 r.group(
-2
+%22path%22
 ))%0A     
@@ -1849,17 +1849,22 @@
 r.group(
-3
+%22line%22
 ))%0A     
@@ -1904,17 +1904,24 @@
 r.group(
-4
+%22column%22
 ))%0A     
@@ -1958,17 +1958,26 @@
 r.group(
-6
+%22category%22
 ))%0A     
@@ -2013,17 +2013,25 @@
 r.group(
-5
+%22message%22
 ))%0A     

use named groups in regex