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 =
            "^\\[(?<severity>CRITICAL|HIGH|MEDIUM|LOW)\\] (?<path>.+):(?<line>\\d+):(?<column>\\d+): (?<message>.*?) \\[(?<category>[^\\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 severity = getSeverity(matcher.group("severity"));
        return builder.setFileName(matcher.group("path"))
                .setSeverity(severity)
                .setLineStart(matcher.group("line"))
                .setColumnStart(matcher.group("column"))
                .setCategory(matcher.group("category"))
                .setMessage(matcher.group("message"))
                .buildOptional();
    }

    private Severity getSeverity(final String severityText) {
        Severity severity;
        if (severityText.contains("CRITICAL")) {
            severity = Severity.ERROR;
        }
        else if (severityText.contains("HIGH")) {
            severity = Severity.WARNING_HIGH;
        }
        else if (severityText.contains("MEDIUM")) {
            severity = Severity.WARNING_NORMAL;
        }
        else {
            severity = Severity.WARNING_LOW;
        }
        return severity;
    }
}

@@ -1750,35 +1750,8 @@
 ) %7B%0A
-        Severity severity;%0A
     
@@ -1794,39 +1794,23 @@
 CAL%22)) %7B
-%0A            severity =
+ return
  Severit
@@ -1817,17 +1817,17 @@
 y.ERROR;
-%0A
+ 
         
@@ -1828,37 +1828,32 @@
       %7D%0A        
-else 
 if (severityText
@@ -1872,35 +1872,23 @@
 IGH%22
-)) %7B%0A            severity =
+    )) %7B return
  Sev
@@ -1906,23 +1906,16 @@
 NG_HIGH;
-%0A      
   %7D%0A    
@@ -1918,21 +1918,16 @@
         
-else 
 if (seve
@@ -1956,35 +1956,21 @@
 IUM%22
+  
 )) %7B
-%0A            severity =
+ return
  Sev
@@ -1994,112 +1994,47 @@
 MAL;
-%0A        %7D%0A        else %7B%0A            severity = Severity.WARNING_LOW;%0A        %7D%0A        return severity
+%7D%0A%0A        return  Severity.WARNING_LOW
 ;%0A  

remove state in `getSeverity`