package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Maps;

public final class MapElementParser extends StringElementParser {

    private static final Pattern ENTRY_PATTERN = new PatternBuilder()
            .appendCapturingPart("[^\\{\\},:]+", "entryname")
            .appendNonCapturingPart(":")
            .appendNonCapturingPart("\\s*")
            .appendCapturingPart(StringElementParser.REPLACE_PATTERN, "entrycontent")
            .build();
    
    @Override
    Pattern createPattern() {
        return new PatternBuilder()
                .appendNonCapturingPart("{")
                .appendNonCapturingPart(ENTRY_PATTERN)
                .openAnonymousParantheses()
                .appendNonCapturingPart("\\s*,\\s*")
                    .appendNonCapturingPart(ENTRY_PATTERN)
                .closeParantheses()
                .zeroOrMore()
                .appendNonCapturingPart("}")
                .build();
    }

    @Override
    void parse(Matcher matcher, StringElementContext context) {
        createMap(matcher, context);
    }
    
    private void createMap(Matcher matcher, StringElementContext context) {
        Map<String,StringElement> entries = Maps.newHashMap();
        Matcher entryMatcher = ENTRY_PATTERN.matcher(matcher.group());
        while (entryMatcher.find()) {
            String name = matcher.group("entryname");
            StringElement element = context.getElementAt(entryMatcher.start(), entryMatcher.end());
            context.removeElement(element);
            entries.put(name, element);
        }
        context.addElement(new MapElement(matcher.start(), matcher.end(), entries));;
    }
}

@@ -472,49 +472,13 @@
 rt(%22
-:%22)%0A            .appendNonCapturingPart(%22
+%5C%5Cs*:
 %5C%5Cs*
@@ -649,14 +649,30 @@
     
-return
+Pattern entryPattern =
  new
@@ -730,17 +730,28 @@
 ngPart(%22
-%7B
+%5B%5E%5C%5C%7B%5C%5C%7D,:%5D+
 %22)%0A     
@@ -781,37 +781,275 @@
 pturingPart(
-ENTRY_PATTERN
+%22%5C%5Cs*:%5C%5Cs*%22)%0A                .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)%0A                .build();%0A        return new PatternBuilder()%0A                .appendNonCapturingPart(%22%5C%5C%7B%22)%0A                .appendNonCapturingPart(entryPattern
 )%0A          
@@ -1074,32 +1074,36 @@
 usParantheses()%0A
+    
                 
@@ -1183,29 +1183,28 @@
 ingPart(
-ENTRY_PATTERN
+entryPattern
 )%0A      
@@ -1304,16 +1304,18 @@
 ngPart(%22
+%5C%5C
 %7D%22)%0A    

Fix some regex bugs in the map parser