package com.ttv.remote;

import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.tandbergtv.watchpoint.pmm.title.ingest.ITitleIngester;
import com.ttv.acs.util.ApplicationProperties;
import com.ttv.acs.util.PConstants;

/**
 * Responsible for building clients for remote services
 * 
 * @author carlos
 * 
 */
public class RemoteClientFactory {

	/**
	 * Obtains a remote ITitleIngester client. This object is obtained through JNDI and should be configured using the jndi.properties file
	 * 
	 * @return
	 * @throws NamingException
	 * @throws IOException 
	 * @throws InvalidPropertiesFormatException 
	 */
	public static ITitleIngester newTitleIngester() throws NamingException, InvalidPropertiesFormatException, IOException {
		String remoteAddress = ApplicationProperties.getInstance().getProperty(PConstants.TITLE_INGESTER_REMOTE_ADDRESS);
		String remoteName = ApplicationProperties.getInstance().getProperty(PConstants.TITLE_INGESTER_REMOTE_NAME);
		
		InitialContext context = getInitialContext(remoteAddress);
		
		Object proxy = context.lookup(remoteName);
		return (ITitleIngester) proxy;
	}

	private static InitialContext getInitialContext(String remoteAddress) throws NamingException {
		Properties properties = new Properties();		
		properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
		properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
		properties.put("java.naming.provider.url", remoteAddress);
		
		InitialContext context = new InitialContext(properties);
		return context;
	}
}
