/******************************************************************************
 * ExternalLogicImpl.java - created by Sakai App Builder -AZ
 * 
 * Copyright (c) 2006 Sakai Project/Sakai Foundation
 * Licensed under the Educational Community License version 1.0
 * 
 * A copy of the Educational Community License has been included in this 
 * distribution and is available at: http://www.opensource.org/licenses/ecl1.php
 * 
 *****************************************************************************/

package org.sakaiproject.wontovlab.logic.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.wontovlab.logic.ExternalLogic;

/**
 * This is the implementation for logic which is external to our app logic
 * @author Sakai App Builder -AZ
 */
public class ExternalLogicImpl implements ExternalLogic {

	private static Log log = LogFactory.getLog(ExternalLogicImpl.class);

	private FunctionManager functionManager;
	public void setFunctionManager(FunctionManager functionManager) {
		this.functionManager = functionManager;
	}

	private ToolManager toolManager;
	public void setToolManager(ToolManager toolManager) {
		this.toolManager = toolManager;
	}

	private SecurityService securityService;
	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}

	private SessionManager sessionManager;
	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	private SiteService siteService;
	public void setSiteService(SiteService siteService) {
		this.siteService = siteService;
	}

	private UserDirectoryService userDirectoryService;
	public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
		this.userDirectoryService = userDirectoryService;
	}
	
	private AuthzGroupService authzGroupService;
	public void setAuthzGroupService(AuthzGroupService authzGroupService) {
		this.authzGroupService = authzGroupService;
	}
	
	private ServerConfigurationService serverConfigurationService;
	public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) {
		this.serverConfigurationService = serverConfigurationService;
	}
	
	

	private void registerFunction(String function)
	{
		if (functionManager.getRegisteredFunctions(function) == null
				|| functionManager.getRegisteredFunctions(function).isEmpty())
			{
				functionManager.registerFunction(function);
			}
	}

	/**
	 * Place any code that should run when this class is initialized by spring here
	 */
	public void init() {
		log.debug("init");
		// register Sakai permissions for this tool
		registerFunction(Experiment_CREATE);
		registerFunction(Experiment_DELETE);
		registerFunction(Experiment_EDIT);
		registerFunction(Experiment_READ);
		
		
		//O codigo abaixo cria as permissoes default para Student, Instructor e Teaching Assistant.
		//Se estiver comentado e necessario setar as permissoes para os roles manualmente em !site.template.course
		/*try 
		{
			AuthzGroup ag = authzGroupService.getAuthzGroup(SITE_TEMPLATE);
			
		    if (authzGroupService.allowUpdate(ag.getId())) 
		    {
		    	Role r = ag.getRole(ag.getMaintainRole());
		    	ag.
		    	r.allowFunction("tool.permission");
		        authzGroupService.save(ag);
		        log.info("Added Permissions to group:" + SITE_TEMPLATE);
		    } 
		    else 
		    {
		    	log.warn("Cannot update authz group: " + SITE_TEMPLATE);
		    }
		} 
		catch (GroupNotDefinedException e) 
		{
		   log.error("Could not find group: " + SITE_TEMPLATE + ", default perms will not be assigned");
		} 
		catch (AuthzPermissionException e) 
		{
		   log.error("Could not save group: " + SITE_TEMPLATE);
		}*/
		
	}


	/* (non-Javadoc)
	 * @see org.sakaiproject.lv.logic.ExternalLogic#getCurrentLocationId()
	 */
	public String getCurrentLocationId() {
		try {
			return toolManager.getCurrentPlacement().getContext();
//			Site s = (Site) siteService.getSite( toolManager.getCurrentPlacement().getContext() );
//			return s.getReference(); // get the entity reference to the site
		} catch (Exception e) {
			return NO_LOCATION;
		}
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.lv.logic.ExternalLogic#getLocationTitle(java.lang.String)
	 */
	public String getLocationTitle(String locationId) {
		try {
			Site site = siteService.getSite(locationId);
			return site.getTitle();
		} catch (IdUnusedException e) {
			log.warn("Cannot get the info about locationId: " + locationId);
			return "----------";
		}
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.lv.logic.ExternalLogic#getCurrentUserId()
	 */
	public String getCurrentUserId() {
		return sessionManager.getCurrentSessionUserId();
	}

	public String getUserDisplayName(String userId) {
		try {
			return userDirectoryService.getUser(userId).getDisplayName();
		} catch (UserNotDefinedException e) {
			log.warn("Cannot get user displayname for id: " + userId);
			return "--------";
		}
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.lv.logic.ExternalLogic#isUserAdmin(java.lang.String)
	 */
	public boolean isUserAdmin(String userId) {
		return securityService.isSuperUser(userId);
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.lv.logic.ExternalLogic#isUserAllowedInLocation(java.lang.String, java.lang.String, java.lang.String)
	 */
	public boolean isUserAllowedInLocation(String userId, String permission, String locationId) 
	{
		String siteRef = siteService.siteReference(locationId);
		if (securityService.unlock(userId, permission, siteRef)) 
		{
			log.debug(userId + " unlocked for " + permission + " at " + siteRef);
			return true;
		}
		log.debug(userId + " cannot be unlocked for " + permission + " at " + siteRef);
		return false;
	}
	
	public String getSakaiPropertyValue(String key)
	{
		return serverConfigurationService.getString(key);
	}
	
	public String getSakaiHomePath()
	{
		return serverConfigurationService.getSakaiHomePath();
	}
	


}
