/*
 * Copyright 2000-2013 JetBrains s.r.o.
 * Copyright 2014-2014 AS3Boyan
 * Copyright 2014-2014 Elias Ku
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.plugins.haxe.compilation;

import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author: Fedor.Korotkov
 */
public class HaxeCompilerError {
  private final CompilerMessageCategory category;
  private final String errorMessage;
  private final String path;
  private final int line;
  private final int column;

  public HaxeCompilerError(CompilerMessageCategory category, String errorMessage, String path, int line, int column) {
    this.category = category;
    this.errorMessage = errorMessage;
    this.path = path;
    this.line = line;
    this.column = column;
  }

  public CompilerMessageCategory getCategory() {
    return category;
  }

  public String getErrorMessage() {
    return errorMessage;
  }

  public String getPath() {
    return path;
  }

  public int getLine() {
    return line;
  }

  public int getColumn() {
    return column;
  }

  @Nullable
  public static HaxeCompilerError create(@NotNull String rootPath, final String message) {
    return create(rootPath, message, true);
  }

    @Nullable
    public static HaxeCompilerError create(@NotNull String rootPath,
                                           final String message,
                                           boolean checkExistence)
    {
        Matcher m;

        // Error: Library ([^\w]+) is not installed(.*)
        if ((m = pLibraryNotInstalled.matcher(message)).matches()) {
            return new HaxeCompilerError(CompilerMessageCategory.WARNING,
                                         "Library " + m.group(1).trim() + 
                                         "is not installed " +
                                         m.group(2).trim(), "", -1, -1);
        }

        // Error:(.*)
        if ((m = pBareError.matcher(message)).matches()) {
            return new HaxeCompilerError(CompilerMessageCategory.ERROR,
                                         m.group(1).trim(), "", -1, -1);
        }

        String rawPath = null, rawLine, rawColumn, text;

        // ([^:]+):([\\d]+): characters ([\\d]+)-[\\d]+ :(.*)
        if ((m = pColumnError.matcher(message)).matches()) {
            rawPath = m.group(1);
            rawLine = m.group(2);
            rawColumn = m.group(3);
            text = m.group(4);
        }
        // ([^:]+):([\\d]+): lines [\\d]+-[\\d]+ :(.*)
        else if ((m = pLineError.matcher(message)).matches()) {
            rawPath = m.group(1);
            rawLine = m.group(2);
            rawColumn = "-1";
            text = m.group(3);
        }
        // Anything that doesn't match error patterns is purely informational
        else {
            return new HaxeCompilerError(CompilerMessageCategory.INFORMATION,
                                         message.trim(), "", -1, -1);
        }

        // Got a real file error, so handle it

        String filePath = FileUtil.toSystemIndependentName(rawPath);
        if (!FileUtil.isAbsolute(filePath)) {
            filePath = rootPath + "/" + filePath;
        }

        if (checkExistence &&
            !(new File(FileUtil.toSystemDependentName(filePath)).exists())) {
            return null;
        }
        
        int line, column;

        try {
            line = Integer.parseInt(rawLine);
        }
        catch (NumberFormatException e) {
            line = -1;
        }

        try {
            column = Integer.parseInt(rawColumn);
        }
        catch (NumberFormatException e) {
            column = -1;
        }

        return new HaxeCompilerError((text.indexOf("Warning") == -1) ?
                                     CompilerMessageCategory.ERROR :
                                     CompilerMessageCategory.WARNING,
                                     text.trim(), filePath, line, column);
    }

    static Pattern pLibraryNotInstalled = Pattern.compile
        ("Error: Library ([\\S]+) is not installed(.*)");
    static Pattern pBareError = Pattern.compile("Error:(.*)");
    static Pattern pColumnError = 
        Pattern.compile("([^:]+):([\\d]+): characters ([\\d]+)-[\\d]+ :(.*)");
    static Pattern pLineError =
        Pattern.compile("([^:]+):([\\d]+): lines [\\d]+-[\\d]+ :(.*)");
}

@@ -3192,16 +3192,23 @@
 group(4)
+.trim()
 ;%0A      
@@ -3449,32 +3449,39 @@
 ext = m.group(3)
+.trim()
 ;%0A        %7D%0A    
@@ -4441,70 +4441,236 @@
     
-return new HaxeCompilerError((text.indexOf(%22Warning%22) == -1) ?
+final String warningStr = %22Warning%22;%0A        if (0 == text.indexOf(warningStr)) %7B%0A          text = text.substring(warningStr.length()).trim();%0A          final String colonChar = %22:%22;%0A          if (0 == text.indexOf(colonChar)) %7B
 %0A   
@@ -4670,35 +4670,82 @@
 ) %7B%0A            
-   
+text = text.substring(colonChar.length()).trim();%0A
                 
@@ -4730,32 +4730,34 @@
 im();%0A          
+%7D%0A
             Comp
@@ -4742,34 +4742,61 @@
     %7D%0A          
-  
+return new HaxeCompilerError(
 CompilerMessageC
@@ -4807,15 +4807,16 @@
 ory.
-ERROR :
+WARNING,
 %0A   
@@ -4849,16 +4849,113 @@
         
+  text, filePath, line, column);%0A        %7D%0A        else %7B%0A          return new HaxeCompilerError(
 Compiler
@@ -4966,33 +4966,33 @@
 ageCategory.
-WARNING,%0A
+ERROR,%0A  
             
@@ -5020,23 +5020,16 @@
     text
-.trim()
 , filePa
@@ -5043,24 +5043,34 @@
 e, column);%0A
+        %7D%0A
     %7D%0A%0A    s

Fix for CompilerWarningMessageParsingUniTest