package com.tandbergtv.watchpoint.pmm.title.conf.specs;

import org.java.plugin.PluginManager;
import org.java.plugin.registry.Extension;
import org.java.plugin.registry.ExtensionPoint;
import org.java.plugin.registry.Extension.Parameter;

import com.tandbergtv.watchpoint.pmm.title.conf.IRightsManager;

/**
 * Creates an instance of the rights manager specified in the plugin and caches
 * the instance for further use throughout the life cycle of the application.
 * 
 * @author spuranik
 * 
 */
public class RightsManagerFactory {

	/*
	 * Instance of rights manager used to validate titles independent of any
	 * spec.
	 */
	private static IRightsManager rightsManager;

	/**
	 * Given the pluginManager and extension point, builds an instance of the
	 * rights manager using the fully qualified class name provided in the
	 * parameter.
	 * 
	 * @param pluginManager
	 * @param point
	 */
	public static void createRightsManager(PluginManager pluginManager,
			ExtensionPoint point) {
		Extension extension = point.getAvailableExtensions().iterator().next();
		createRightsManager(pluginManager, extension);
	}

	private static void createRightsManager(PluginManager pluginManager,
			Extension extension) {
		/* expects the rights manager class to be specified in this parameter */
		Parameter classParameter = extension.getParameter("class");
		String className = (classParameter != null) ? classParameter
				.valueAsString() : null;

		/* make sure there is always a rights manager configured. */
		if (className == null || className.trim().length() == 0) {
			throw new RuntimeException(
					"Rights manager is not configured. "
							+ "Make sure to set the class for rights manager in the plugin "
							+ "'com.tandbergtv.metadata.rightsmanager'");
		}

		ClassLoader loader = pluginManager.getPluginClassLoader(extension
				.getDeclaringPluginDescriptor());

		Class<IRightsManager> clazz;
		try {
			clazz = (Class<IRightsManager>) loader.loadClass(className);
			rightsManager = clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("Failed to create instance of "
					+ className, e);
		}
	}

	public static IRightsManager getRightsManager() {
		return rightsManager;
	}
}
