package com.k_int.ciim.ui.system;

import java.util.Set;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import com.k_int.ciim.data.dto.DataException;
import com.k_int.ciim.data.util.CacheManager;
import com.k_int.ciim.ref.MuseumDataTypeEnum;
import com.sun.jersey.api.view.Viewable;

@Path("/system")
public class SystemManager implements ApplicationContextAware
{
	private String[] data_types = null;
	
	@XmlTransient
	private static Log log = LogFactory.getLog(SystemManager.class);
	@XmlTransient
	private SessionFactory factory = null;	
	@XmlTransient
	private ApplicationContext ctx;

	public void setApplicationContext(ApplicationContext ctx) { this.ctx = ctx; }
	public void setSessionFactory(SessionFactory factory) {	this.factory = factory; }
	
	public SystemManager(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml() 
	{
		return new Viewable("index",this);
	}
	
	public String[] getDataTypes() 
	{
		CacheManager cache_manager = (CacheManager) ctx.getBean("CacheManager"); 
		
		try
		{
			Session session = SessionFactoryUtils.getSession(factory, true);
			
			Set<MuseumDataTypeEnum> types = cache_manager.getDataTypes(session);	
			int counter = 0;
			
			if(types != null && types.size() > 0)
			{
				data_types = new String[types.size()];
				for(MuseumDataTypeEnum data_type_val : types)
				{
					data_types[counter] = data_type_val.toString();
					counter++;
				}
			}
			else
			{
				data_types = new String[MuseumDataTypeEnum.values().length];
				
				for(MuseumDataTypeEnum data_type_val : MuseumDataTypeEnum.values())
				{
					data_types[counter] = data_type_val.toString();
					counter++;
				}
			}
		}
		catch(DataException de)
		{
			log.error("Unable to retrieve data types (in use) from cache manager.");
		}
		
		return data_types;
	}
	
}
