package gutenberg.util;

import com.google.common.collect.Maps;

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

/**
 * @author <a href="http://twitter.com/aloyer">@aloyer</a>
 */
public class Attributes {

    private static Pattern KEY_VALUE = Pattern.compile("([a-zA-Z_\\-]+)" + "\\s*[=:]\\s*" + "(\"[^\"]+\"|[^\",]+)");

    private final Map<String, String> map;

    public Attributes() {
        this.map = Maps.newHashMap();
    }

    public Attributes declare(String key, String value) {
        map.put(key.toLowerCase(), value);
        return this;
    }

    public Attributes appendCommaSeparatedKeyValuePairs(String text) {
        Matcher matcher = KEY_VALUE.matcher(text);
        while (matcher.find()) {
            String key = matcher.group(1);
            String value = unquote(matcher.group(2));
            map.put(key, value);
        }
        return this;
    }

    private String unquote(String group) {
        if (group.startsWith("\""))
            return group.substring(1, group.length() - 1);
        else
            return group;
    }

    public String getString(String key) {
        return map.get(key);
    }

    public boolean isOn(String key) {
        String val = map.get(key);
        if (val == null)
            return false;
        else
            return val.equalsIgnoreCase("on") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("true");
    }

    public boolean isOff(String key) {
        String val = map.get(key);
        if (val == null)
            return false;
        else
            return val.equalsIgnoreCase("off") || val.equalsIgnoreCase("no") || val.equalsIgnoreCase("false");
    }

    public Dimension getDimension(String key) throws DimensionFormatException {
        String val = map.get(key);
        if (val != null)
            return new DimensionParser().parse(val);
        else
            return null;
    }

    @Override
    public String toString() {
        return "Attributes{" + map + '}';
    }
}

@@ -387,22 +387,22 @@
 String, 
-String
+Object
 %3E map;%0A%0A
@@ -514,22 +514,22 @@
 ng key, 
-String
+Object
  value) 
@@ -1164,16 +1164,25 @@
   return
+ (String)
  map.get
@@ -1246,39 +1246,41 @@
    String val = 
-map.get
+getString
 (key);%0A        i
@@ -1503,39 +1503,41 @@
    String val = 
-map.get
+getString
 (key);%0A        i
@@ -1793,30 +1793,30 @@
 n %7B%0A        
-String
+Object
  val = map.g
@@ -1844,17 +1844,17 @@
 val 
-!
+=
 = null)%0A
     
@@ -1841,32 +1841,97 @@
 f (val == null)%0A
+            return null;%0A        else if (val instanceof String)%0A
             retu
@@ -1961,16 +1961,24 @@
 ).parse(
+(String)
 val);%0A  
@@ -2003,27 +2003,38 @@
      return 
-nul
+(Dimension) va
 l;%0A    %7D%0A%0A  

Prepare attributes for generalization