package junkutil.text;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junkutil.common.NullUtil;
import junkutil.common.StringUtil;
import junkutil.set.LzList;
import junkutil.set.LzMap;

/**
 * 正規表現エンジンをテストする。
 * @author Hiroyuki Shiota
 */
public class RegExpUtilTest extends TestCase {
	/**
	 * コンストラクタ
	 * @param name
	 */
	public RegExpUtilTest(String name) {
		super(name);
	}

	/**
	 * @return
	 */
	public static Test suite() {
		TestSuite test = new TestSuite("RegExpUtilTest");
		test.addTest(new TestSuite(RegExpUtilTest.class));
	
		return test;
	}

	/**
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
	}

	/**
	 * @see junit.framework.TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
	}

	/**
	 * @throws Exception
	 */
	public void testReplaceBack() throws Exception {
		String result = new RegExpUtil().replace("http://hoge/foo/bar.html", "/", new RegExpCallback(){
			public String getReplaced(StringBuffer buff, Matcher matcher) {
				return "_";
			}
		});
		assertTrue(result.equals("http:__hoge_foo_bar.html"));
	}
	
	public void testTemplate() throws Exception {
		RegExpUtil re = new RegExpUtil();
		String test1 = "aaa${foo}bbb${bar}ccc${hoge}ddd${piyo}eee";
		String placeHolderRE = "\\$\\{([^\\${}]+)\\}";
		TemplateCallback callback = new TemplateCallback();
		LzMap vars = new LzMap(new String[]{
				"foo", "FOO",
				"bar", "BAR",
				"hoge", "HOGE"
		});
		callback.setValues(vars.map());
		String replaced = re.replace(test1, placeHolderRE, callback);
		assertTrue(replaced.equals("aaa[FOO]bbb[BAR]ccc[HOGE]ddd[null]eee"));
	}
	
	public static class TemplateCallback implements RegExpCallback {
		private Map values;
		public String getReplaced(StringBuffer buff, Matcher matcher)  {
			String valueName = matcher.group(1);
			Object valueObj = values.get(valueName);
			String valueStr = NullUtil.nvlObject(valueObj, "null").toString();
			return "[" + valueStr + "]";
		}
		public Map getValues() {
			return values;
		}
		public void setValues(Map values) {
			this.values = values;
		}
	}

}
