/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.adapter;

import java.util.HashMap;

import junit.framework.TestCase;
import woolpack.container.ContainerContext;
import woolpack.container.ContainerUtils;
import woolpack.factory.FactoryUtils;
import woolpack.fn.Fn;
import woolpack.fn.FnUtils;
import woolpack.utils.Utils;
import woolpack.web.SimpleWebContext;
import woolpack.web.WebContext;
import woolpack.web.WebUtils;

public class OGNLUtilsTest extends TestCase {
	
	public void testOGNL() throws Exception {
		OGNLUtils.setting();
		final ContainerContext<Object> context = new ContainerContext<Object>();
		context.setFn(FnUtils.exec(FnUtils.join(
				ContainerUtils.getKey(),
				FnUtils.switching(
						Utils.<Object, Fn<? super ContainerContext<Object>, ?, ? extends Exception>>
						map("key0", FnUtils.fix("value0"))
						.map("key1", FnUtils.fix("value1"))
						.map("key2", FactoryUtils.doEL(new OGE("#{\"myKey0\":key0, \"myKey1\":key1}")))
				))));
		assertEquals("value0", context.visit("key0"));
		assertEquals("value1", context.visit("key1"));
		assertEquals(Utils.map("myKey0", "value0").map("myKey1", "value1"), context.visit("key2"));
	}
	
	public void testWeb() throws Exception {
		OGNLUtils.setting();
		final ContainerContext<WebContext> context = new ContainerContext<WebContext>();
		context.setFn(FnUtils.exec(FnUtils.join(
				ContainerUtils.getKey(),
				FnUtils.switching(
					Utils.<Object, Fn<? super ContainerContext<WebContext>, ?, ? extends Exception>>
					map("s", FnUtils.fix("sa"))
					.map("r", WebUtils.request(FnUtils.fix("ra")))
					.map("a", WebUtils.application(FnUtils.fix("aa")))
					.map("z", WebUtils.session(FactoryUtils.doEL(new OGE("#{\"r\":r, \"s\":s, \"a\":a}"))))
			))));
		final SimpleWebContext webContext = new SimpleWebContext();
		webContext.setRequest(new HashMap<String, Object>());
		webContext.setSession(Utils.concurrentMap(new HashMap<String, Object>(), new Object()));
		webContext.setApplication(Utils.concurrentMap(new HashMap<String, Object>(), new Object()));
		context.setSubContext(webContext);
		final Object result = context.visit("z");
		assertEquals(Utils.map("r", "ra").map("s", "sa").map("a", "aa"), result);
		assertSame(result, webContext.getSession().get("woolpack.web.WebUtils.z"));
	}
}
