package com.sifang.modules.sys.util;


import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author gaols
 */
public class TrimStrMap implements Map<String, String> {

    private final Map<String, String> internalMap;
    private boolean safe = true;
    private static final Pattern UNSAFE_MATCHER = Pattern.compile("[%']");

    public TrimStrMap(Map<String, String> internalMap) {
        this(internalMap, true);
    }

    public TrimStrMap(Map<String, String> internalMap, boolean safe) {
        this.internalMap = internalMap;
        this.safe = safe;

        if (internalMap == null) {
            throw new IllegalArgumentException("wrapped map cannot null");
        }
    }

    @Override
    public int size() {
        return internalMap.size();
    }

    @Override
    public boolean isEmpty() {
        return internalMap.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return internalMap.containsKey(key);
    }

    public boolean hasNonBlankValue(String key) {
        String value = get(key);
        return StringUtils.isNotBlank(value);
    }

    @Override
    public boolean containsValue(Object value) {
        return internalMap.containsValue(value);
    }

    @Override
    public String get(Object key) {
        String o = internalMap.get(key);
        String ret = StringUtils.trim(o);
        if (ret == null) {
            return null;
        }

        return safe ? UNSAFE_MATCHER.matcher(ret).replaceAll("") : ret;
    }

    public String getRaw(Object key) {
        return internalMap.get(key);
    }

    @Override
    public String put(String key, String value) {
        return internalMap.put(key, value);
    }

    @Override
    public String remove(Object key) {
        return internalMap.remove(key);
    }

    @Override
    public void putAll(Map<? extends String, ? extends String> m) {
        internalMap.putAll(m);
    }

    @Override
    public void clear() {
        internalMap.clear();
    }

    @Override
    public Set<String> keySet() {
        return internalMap.keySet();
    }

    @Override
    public Collection<String> values() {
        return internalMap.values();
    }

    @Override
    public Set<Entry<String, String>> entrySet() {
        return internalMap.entrySet();
    }

    public TrimStrMap safe() {
        safe = true;
        return this;
    }

}
