/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (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.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.conf.module;

import java.security.Principal;
import java.util.*;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.module.ModuleConfigurationData;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
import com.silverwrist.venice.VeniceNamespaces;
import com.silverwrist.venice.community.CommunityServiceInstall;
import com.silverwrist.venice.util.*;
import com.silverwrist.venice.conf.ConfNamespaces;
import com.silverwrist.venice.conf.iface.UseCount;

public class ModuleMain implements ModuleFunctions, UseCount
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  public static final String SERVICE_NAME = "conferencing.service";
  public static final String CONTROLLER_OBJNAME = "controller";
  public static final String SHORTVAR = "CONFERENCING";

  private static final QualifiedNameKey NAME =
      new QualifiedNameKey(ConfNamespaces.CONFERENCING_NAMESPACE,"Venice.conferencing");
  private static final String RESOURCES = "com.silverwrist.venice.conf.module.ModuleMessages";

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private int m_usecount = 0;
  private ModuleSite m_site = null;
  private Controller m_controller = null;
  private ComponentShutdown m_res1;
  private ComponentShutdown m_res2;

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  public ModuleMain()
  { // do nothing
  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface ModuleFunctions
   *--------------------------------------------------------------------------------
   */

  public QualifiedNameKey getModuleID()
  {
    return NAME;

  } // end getModuleID

  public String getDescription()
  {
    ResourceBundle b = ResourceBundle.getBundle(RESOURCES);
    return b.getString("description");

  } // end getDescription

  public void initialize(ModuleSite site, ServiceProvider services) throws ModuleException
  {
    m_site = site;

    try
    { // Mount the resource provider into the resource tree.
      ResourceProvider module_res = site.getResourceProvider();
      ResourceProviderManager resmgr = (ResourceProviderManager)(services.queryService(ResourceProviderManager.class));
      m_res1 = resmgr.mountResourceProvider("/scripts/conf",new PrefixResourceProvider(module_res,"/scripts"));
      m_res2 = resmgr.mountResourceProvider("/velocity/conf",new PrefixResourceProvider(module_res,"/velocity"));

    } // end try
    catch (ConfigException e)
    { // translate the ConfigException into a ModuleException
      throw new ModuleException(e);

    } // end catch

  } // end initialize

  public void shutdown()
  {
    m_res1.shutdown();
    m_res1 = null;
    m_res2.shutdown();
    m_res2 = null;
    m_site = null;
    m_controller = null;
    m_usecount = 0;

  } // end shutdown

  public boolean inUse()
  {
    return (m_usecount>0);

  } // end inUse

  public boolean canInstall(ServiceProvider services, Principal installer)
  {
    try
    { // get the module configuration data to get the SRM name, then use that to get the actual SRM, then get
      // the global ACL, then test permissions
      ModuleConfigurationData conf_data =
          (ModuleConfigurationData)(services.queryService(ModuleConfigurationData.class));
      String srm_name = conf_data.getValue(Namespaces.DYNAMO_OBJECT_NAMESPACE,"security");
      SecurityReferenceMonitor srm =
          (SecurityReferenceMonitor)(GetObjectUtils.getDynamoComponent(services,SecurityReferenceMonitor.class,
								       srm_name));
      DynamoAcl gacl = srm.getGlobalAcl();
      return gacl.testPermission((DynamoUser)installer,VeniceNamespaces.SYSTEM_PERMS_NAMESPACE,"edit.menus");

    } // end try
    catch (Exception e)
    { // unable to test permission
      return false;

    } // end catch

  } // end canInstall

  public void install(ModuleSite site, ServiceProvider services, Principal installer, DynamoLog log)
      throws ModuleException
  {
    synchronized (this)
    { // create Controller object if necessary
      if (m_controller==null)
	m_controller = new Controller(this);

    } // end synchronized block

    ResourceBundle bun = ResourceBundle.getBundle(RESOURCES);

    try
    { // Install our community menu options.
      CommunityMenuInstaller comm_menu = new CommunityMenuInstaller(services);
      comm_menu.installCommunityServiceEntry((DynamoUser)installer,bun.getString("comm.menu.prompt"),"SERVLET",
					     "conf/conferences.js.vs?cc=${cid}",SHORTVAR);
      log.info("Installed conferencing option to community left menu");

    } // end try
    catch (DatabaseException de)
    { // database error
      log.error("Caught database error while installing menus",de);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","install.cmenu.fail",de);
      me.setParameter(0,de.getMessage());
      throw me;

    } // end catch
    catch (DynamoSecurityException dse)
    { // security error
      log.error("Caught security error while installing menus",dse);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","install.cmenu.fail",dse);
      me.setParameter(0,dse.getMessage());
      throw me;

    } // end catch

    try
    { // Install our community service.
      CommunityServiceInstall csi = (CommunityServiceInstall)(services.queryService(CommunityServiceInstall.class));
      csi.installService(ConfNamespaces.CONFERENCING_NAMESPACE,SERVICE_NAME,site.getHandle(),
			 ConfNamespaces.CONFERENCING_NAMESPACE,CONTROLLER_OBJNAME,m_controller,SHORTVAR);
      log.info("Installed service " + ConfNamespaces.CONFERENCING_NAMESPACE + "::" + SERVICE_NAME);

    } // end try
    catch (DatabaseException de)
    { // whoops! that didn't work!
      log.error("Caught database error while installing service",de);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","install.service.fail",de);
      me.setParameter(0,de.getMessage());
      throw me;

    } // end catch

  } // end install

  public void uninstall(ModuleSite site, ServiceProvider services, Principal uninstaller, DynamoLog log)
      throws ModuleException
  {
    try
    { // uninstall the community service
      CommunityServiceInstall csi = (CommunityServiceInstall)(services.queryService(CommunityServiceInstall.class));
      csi.removeService(ConfNamespaces.CONFERENCING_NAMESPACE,SERVICE_NAME);
      log.info("Removed service " + ConfNamespaces.CONFERENCING_NAMESPACE + "::" + SERVICE_NAME);

    } // end try
    catch (DatabaseException de)
    { // whoops! that didn't work!
      log.error("Caught database error while uninstalling service",de);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","uninstall.service.fail",de);
      me.setParameter(0,de.getMessage());
      throw me;

    } // end catch

    try
    { // uninstall the community menus
      CommunityMenuInstaller comm_menu = new CommunityMenuInstaller(services);
      comm_menu.removeCommunityServiceEntry((DynamoUser)uninstaller,"conf/conferences.js.vs",SHORTVAR);
      log.info("Removed conferencing option from community left menu");

    } // end try
    catch (DatabaseException de)
    { // database error
      log.error("Caught database error while uninstalling menus",de);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","uninstall.cmenu.fail",de);
      me.setParameter(0,de.getMessage());
      throw me;

    } // end catch
    catch (DynamoSecurityException dse)
    { // security error
      log.error("Caught security error while uninstalling menus",dse);
      ModuleException me = new ModuleException(ModuleMain.class,"ModuleMessages","uninstall.cmenu.fail",dse);
      me.setParameter(0,dse.getMessage());
      throw me;

    } // end catch

  } // end uninstall

  public DynamicObject getProvidedObject(String namespace, String name) throws ModuleException
  {
    if (ConfNamespaces.CONFERENCING_NAMESPACE.equals(namespace) && CONTROLLER_OBJNAME.equals(name))
    { // we want the community service controller
      synchronized (this)
      { // create it if necessary
	if (m_controller==null)
	  m_controller = new Controller(this);
	return m_controller;

      } // end synchronized block

    } // end if

    return null;

  } // end getProvidedObject

  /*--------------------------------------------------------------------------------
   * Implementations from interface UseCount
   *--------------------------------------------------------------------------------
   */

  public synchronized void incrementUseCount()
  {
    m_usecount++;

  } // end incrementUseCount

  public synchronized void decrementUseCount()
  {
    m_usecount--;

  } // end decrementUseCount

} // end class ModuleMain
