package org.sonar.javascript.angular.checks;

import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.javascript.angular.util.AngularUtil;
import org.sonar.javascript.tree.visitors.CharsetAwareVisitor;
import org.sonar.plugins.javascript.api.tree.Tree;
import org.sonar.plugins.javascript.api.tree.expression.LiteralTree;
import org.sonar.plugins.javascript.api.visitors.BaseTreeVisitor;
import org.sonar.squidbridge.annotations.SqaleConstantRemediation;
import org.sonar.squidbridge.annotations.SqaleSubCharacteristic;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by thibaud.bourgeois on 19/12/2015.
 * HTML use check.
 */
@Rule(
    key = "NGR2",
    priority = Priority.CRITICAL,
    name = "HTML in controller should not be used.",
    tags = {"convention"},
    description = "Create a directive or template instead."
)
@SqaleSubCharacteristic(RulesDefinition.SubCharacteristics.DATA_RELIABILITY)
@SqaleConstantRemediation("10min")
public class HtmlUseCheck extends BaseTreeVisitor implements CharsetAwareVisitor {

    Charset charset;
    Pattern htmlPattern = Pattern.compile("<(\"[^\"]*\"|'[^']*'|[^'\">])*>");

    @Override
    public void setCharset(Charset charset) {
        this.charset = charset;
    }

    @Override
    public void visitLiteral(LiteralTree tree) {

        if (tree.is(Tree.Kind.STRING_LITERAL)
                && AngularUtil.isController(getContext().getFile(), charset)) {
            Matcher matcher = htmlPattern.matcher(tree.value());
            if (matcher.find()) {
                getContext().addIssue(this, tree, "Remove HTML templating in controller, create a directive or a template instead");
            }
        }
        super.visitLiteral(tree);
    }

}

@@ -587,16 +587,37 @@
 istic;%0A%0A
+import java.io.File;%0A
 import j
@@ -1509,32 +1509,19 @@
  && 
-AngularUtil.isController
+isForbidden
 (get
@@ -1543,17 +1543,8 @@
 le()
-, charset
 )) %7B
@@ -1792,32 +1792,32 @@
     %7D%0A        %7D%0A
-
         super.vi
@@ -1841,10 +1841,287 @@
 %0A    %7D%0A%0A
+    private boolean isForbidden(File file) %7B%0A        return AngularUtil.isController(file, charset)%0A                %7C%7C AngularUtil.isFactory(file, charset)%0A                %7C%7C AngularUtil.isProvider(file, charset)%0A                %7C%7C AngularUtil.isService(file, charset);%0A    %7D%0A%0A
 %7D%0A

add HTML forbidden files to rule