package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Lists;

public final class ListElementParser extends StringElementParser {

    @Override
    Pattern createPattern() {
        return new PatternBuilder()
                .openNamedParantheses("list")
                    .appendNonCapturingPart("[")
                    .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                    .openAnonymousParantheses()
                    .appendNonCapturingPart("\\s*,\\s*")
                        .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                    .closeParantheses()
                    .zeroOrMore()
                    .appendNonCapturingPart("]")
                .closeParantheses()
                .or()
                .build();
    }

    @Override
    void parse(Matcher matcher, StringElementContext context) {
        createList(matcher, context);
    }
    
    private void createList(Matcher matcher, StringElementContext context) {
        List<StringElement> elements = Lists.newArrayList();
        Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group());
        while (elementMatcher.find()) {
            StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end());
            context.removeElement(element);
            elements.add(element);
        }
        context.addElement(new ListElement(matcher.start(), matcher.end(), elements));;
    }
}

@@ -386,58 +386,8 @@
 r()%0A
-                .openNamedParantheses(%22list%22)%0A    
     
@@ -427,16 +427,14 @@
 rt(%22
+%5C%5C
 %5B%22)%0A
-    
     
@@ -498,36 +498,32 @@
 EPLACE_PATTERN)%0A
-    
                 
@@ -619,36 +619,32 @@
                 
-    
 .appendNonCaptur
@@ -680,36 +680,32 @@
 EPLACE_PATTERN)%0A
-    
                 
@@ -740,20 +740,16 @@
         
-    
 .zeroOrM
@@ -754,20 +754,16 @@
 rMore()%0A
-    
         
@@ -799,68 +799,12 @@
 rt(%22
+%5C%5C
 %5D%22
-)%0A                .closeParantheses()%0A                .or(
 )%0A  

Fix some bugs in the list parser regex