/**
 * ContainerCacheTests.java
 * Created on May 16, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.util.unitTests;

import java.io.Serializable;

import junit.framework.TestCase;

import com.tandbergtv.watchpoint.pmm.dao.hibernate.HibernateContext;
import com.tandbergtv.watchpoint.pmm.entities.IContainer;
import com.tandbergtv.watchpoint.pmm.entities.Partner;
import com.tandbergtv.watchpoint.pmm.entities.PartnerType;
import com.tandbergtv.watchpoint.pmm.util.ContainerCacheActivator;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.core.service.cache.ICacheService;

/**
 * @author spuranik
 *
 */
public class ContainerCacheTests extends TestCase {

	private ContainerCacheActivator activator;

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		try {
			HibernateContext.getContext().initializeContext();

			activator = new ContainerCacheActivator();
			activator.start();

		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
		}
		super.setUp();
	}

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		try {
			HibernateContext.getContext().closeContext();
			activator.stop();
		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
		}
		super.tearDown();
	}

	@SuppressWarnings("unchecked")
	public void testGettingContainer() {
		try {
			ICacheService<IContainer> cc = (ICacheService<IContainer>) ServiceRegistry.getDefault()
					.lookup("Container Cache");
			long contextId = 1;
			// wait for some time before the cache gets populated
			Thread.sleep(10000);
			IContainer container = cc.get(contextId);
			printContainer(container);

			// add new partner
			Partner p = new Partner();
			p.setId(4L);
			p.setName("some partner");
			p.setType(PartnerType.DISTRIBUTION);
			cc.add(4L, p);
			container = cc.get(4L);
			printContainer(container);

			// update this latest partner
			p.setName("Modified name");
			cc.add(4L, p);
			printContainer(container);

			cc.remove(4L);
			System.out.println("Current cache contextIds:");
			for (Serializable id : cc.getKeys()) {
				System.out.println(id);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * @param container
	 * 	container whose properties will be printed.
	 */
	private void printContainer(IContainer container) {
		System.out.println("Container Id: " + container.getContainerId());
		System.out.println("Container Name: " + container.getContainerName());
		System.out.println("Container Type: " + container.getContainerType().toString());
	}
}
