/*
 * 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.test.ee;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import woolpack.test.TestUtils;

import junit.framework.TestCase;

public class EETestUtilsTest extends TestCase {
	private final List<String> boundList = new ArrayList<String>();
	private final List<String> unboundList = new ArrayList<String>();
	
	public void testNormal(){
		final ConcurrentMap<String,Object> map = EETestUtils.generateSession();
		
		map.put("key0", getListener("value00"));
		assertTrue(TestUtils.equals(Arrays.asList("value00"), boundList));
		assertTrue(TestUtils.equals(Collections.emptyList(), unboundList));
		
		map.put("key1", new Object());
		assertTrue(TestUtils.equals(Arrays.asList("value00"), boundList));
		assertTrue(TestUtils.equals(Collections.emptyList(), unboundList));
		
		map.put("key0", getListener("value01"));
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01"), boundList));
		assertTrue(TestUtils.equals(Arrays.asList("value00"), unboundList));
		
		map.remove("key0");
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01"), boundList));
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01"), unboundList));
		
		map.put("key0", getListener("value02"));
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01", "value02"), boundList));
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01"), unboundList));
		
		map.keySet().remove("key0");
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01", "value02"), boundList));
		assertTrue(TestUtils.equals(Arrays.asList("value00", "value01", "value02"), unboundList));
	}
	
	private Object getListener(final String s){
		return new HttpSessionBindingListener(){
			public void valueBound(final HttpSessionBindingEvent arg0) {
				boundList.add(s);
			}
			public void valueUnbound(final HttpSessionBindingEvent arg0) {
				unboundList.add(s);
			}
		};
	}
}
