package com.ejie.ab63.util;

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

public class SimpleNode extends Node {
	String key;
	String value;

	SimpleNode(String key, String value) {
		this.key = key;
		this.value = value;
	}

	@Override
	public String toString() {
		if (value == null) {
			value = "";
		}
		return "{0} = {1}".replace("{0}", key).replace("{1}", value);
	}

	@Override
	Node find(String search) {
		return !"".equals(search) && key.equals(search) ? this : null;
	}

	@Override
	Node find(String search, boolean wildcard) {
		if (wildcard) {
			boolean hasIdHash = search.indexOf('#') > -1;
			if (hasIdHash) {
				String pattern = search.replace(".", "\\.").replace("#", ".+");
				return Pattern.compile(pattern).matcher(key).matches() ? this : null;
			}
		}
		return find(search);
	}

	@Override
	String getNodeType() {
		return NODE_TYPE_SIMPLE;
	}

	@Override
	public void print() {
		System.out.println(toString());
	}

	@Override
	protected String print(int deep) {
		if (value == null) {
			value = "";
		}
		if (deep == 0) {
			return String.format("%s = %s%n", key, value);
		} else {
			return String.format("%-" + deep + "s%s=%s%n", " ", key, value).replace(" ", "-");

		}

	}

	@Override
	public Map<String, String> map(Map<String, String> map) {
		map.put(key, value);
		return map;
	}

	@Override
	public Map<String, String> map(Map<String, String> map, int deep, int limit) {
		if (deep < limit) {
			map.put(key, value);
		}
		return map;
	}

}