package org.wikimedia.commons.modifications;

import org.json.JSONException;
import org.json.JSONObject;

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

public class TemplateRemoveModifier extends PageModifier {

    public static final String MODIFIER_NAME = "TemplateRemoverModifier";

    public static final String PARAM_TEMPLATE_NAME = "template";

    public static final Pattern PATTERN_TEMPLATE_OPEN = Pattern.compile("\\{\\{");
    public static final Pattern PATTERN_TEMPLATE_CLOSE = Pattern.compile("\\}\\}");


    public TemplateRemoveModifier(String templateName) {
        super(MODIFIER_NAME);
        try {
            params.putOpt(PARAM_TEMPLATE_NAME, templateName);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public TemplateRemoveModifier(JSONObject data) {
        super(MODIFIER_NAME);
        this.params = data;
    }

    @Override
    public String doModification(String pageName, String pageContents) {
        String templateRawName = params.optString(PARAM_TEMPLATE_NAME);
        // Wikitext title normalizing rules. Spaces and _ equivalent
        // They also 'condense' - any number of them reduce to just one (just like HTML)
        String templateNormalized = templateRawName.trim().replaceAll("(\\s|_)+", "(\\s|_)+");

        // Not supporting {{ inside <nowiki> and HTML comments yet
        // (Thanks to marktraceur for reminding me of the HTML comments exception)
        Pattern templateStartPattern = Pattern.compile("\\{\\{" + templateNormalized, Pattern.CASE_INSENSITIVE);
        Matcher matcher = templateStartPattern.matcher(pageContents);

        while(matcher.find()) {
            int braceCount = 1;
            int startIndex = matcher.start();
            int curIndex = matcher.end();
            while(curIndex < pageContents.length()) {
                if(PATTERN_TEMPLATE_OPEN.matcher(pageContents).find(curIndex)) {
                    braceCount++;
                } else if(PATTERN_TEMPLATE_CLOSE.matcher(pageContents).find(curIndex)) {
                    braceCount--;
                }
                curIndex++;
                if(braceCount == 0) {
                    break;
                }
            }

            // Strip trailing whitespace
            while(curIndex < pageContents.length()) {
                if(pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') {
                    curIndex++;
                } else {
                    break;
                }
            }

            // I am so going to hell for this, sigh
            pageContents = pageContents.substring(0, startIndex) + pageContents.substring(curIndex);
            matcher = templateStartPattern.matcher(pageContents);
        }

        return pageContents;

    }

    @Override
    public String getEditSumary() {
        return "Removed template " + params.optString(PARAM_TEMPLATE_NAME) + ".";
    }
}

@@ -1826,69 +1826,106 @@
     
-while(curIndex %3C pageContents.length()) %7B%0A                if(
+Matcher openMatch = PATTERN_TEMPLATE_OPEN.matcher(pageContents);%0A            Matcher closeMatch = 
 PATT
@@ -1929,36 +1929,37 @@
 ATTERN_TEMPLATE_
-OPEN
+CLOSE
 .matcher(pageCon
@@ -1968,229 +1968,692 @@
 nts)
-.find(curIndex)) %7B%0A                    braceCount++;%0A                %7D else if(PATTERN_TEMPLATE_CLOSE.matcher(pag
+;%0A%0A            while(curIndex %3C pageContents.length()) %7B%0A                boolean openFound = openMatch.find(curIndex);%0A                boolean closeFound = closeMatch.find(curIndex);%0A%0A                if(openFound && (!closeFound %7C%7C openMatch.start() %3C closeMatch.start())) %7B%0A                    brac
 eCo
+u
 nt
-ents).find(curIndex)) %7B%0A                    braceCount--;%0A                %7D%0A                curIndex++;
+++;%0A                    curIndex = openMatch.end();%0A                %7D else if (closeFound) %7B%0A                    braceCount--;%0A                    curIndex = closeMatch.end();%0A                %7D else if (braceCount %3E 0) %7B%0A                    // The template never closes, so...remove nothing%0A                    curIndex = startIndex;%0A                    break;%0A                %7D%0A
 %0A   
@@ -2667,16 +2667,17 @@
       if
+ 
 (braceCo
@@ -2684,24 +2684,80 @@
 unt == 0) %7B%0A
+                    // The braces have all been closed!%0A
             

Make template removal work properly