/*
ESUP-portail is a french academic project developed under the GPL (General Public License) augmented according to the following :
A binary or source file developped by ESUP-portail can be used or compiled with products under Apache license.
The official english text of the GPL can be found here : http://www.gnu.org/licenses/gpl.html .
A non official french translation can be found here : http://www.linux-France.org/article/these/gpl.html .
The different kinds of licenses governing the products developed by the Apache foundation can be found here : http://www.apache.org/licenses .
It follows that you can as well as use download contents as well modify and redistribute them provided you respect the GPL terms.
Downloading and using such contents do not provide any guaranty.
Be sure that you have well understood the terms of the license before using the contents it covers.
The ESUP-portail distribution includes the following distributions :
    * UPortal :
      software developed by JA-SIG (Java Architecture - Special Interest Group)
      You can find the license page here : http://mis105.udel.edu/ja-sig/uportal/license.html
    * CAS :
      SSO solution developed by Yale University
      You can find the project page here : http://www.yale.edu/tp/auth
    * Cocoon :
      XML framework distributed by the Apache foundation under Apache license;
      Please find the full text here : http://cocoon.apache.org/2.1/license.html
    * Mod_dav:
      A DAV module for Apache web server
      You can find the project page here : http://www.webdav.org/mod_dav
    * IMP :
      webmail from Horde application framework
      You can find the project page here : http://www.horde.org
    * …. To be completed
*/
package org.esupportail.portal.channels.CStockage.spacesPersonalization;

import java.util.ArrayList;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.esupportail.portal.channels.CStockage.channelAction.classic.sharing.SharedSpaceProperties;
import org.esupportail.portal.channels.CStockage.config.ChannelConfiguration;
import org.esupportail.portal.channels.CStockage.config.Space;
import org.esupportail.portal.channels.CStockage.exception.DataBaseException;
import org.esupportail.portal.channels.CStockage.exception.PropertiesException;
import org.esupportail.portal.channels.CStockage.exception.ServerException;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.DataBaseAccess;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.ServerTool;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.UserForPersonalization;

/**
 * Id: PersonalizationTool.java,v 1.0 13 janv. 2005
 * Copyright (c) 2005 Esup Portail (www.esup-portail.org)
 * Classes: PersonalizationTool
 * Original Author: Yohan Colmant
 * This class is a tool used to manage the sharing actions
 */
public class PersonalizationTool {

	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(PersonalizationTool.class);
	
	
	/**
	 * The object used to access the database
	 */
	private DataBaseAccess dbAccess;
	
	
	/**
	 * If the server into the database is administrated
	 */
	public static final String ADMINISTRATED_SERVER = "administrated_server";

	
	/**
	 * Constructor
	 * @throws PropertiesException
	 */
	public PersonalizationTool() throws PropertiesException {
		dbAccess = new DataBaseAccess();		
	}
	

	


	
	/******************
	 * PERSONALIZATION 
	 *****************/
	
	
	
	

	/**
	 * Get the available spaces for a user or a group
	 * @param targetKey the key of the target
	 * @param targetType if we get spaces for user or a group, or all ?
	 * @param userPortalLogin the login of the user in the portal
	 * @param obliged if the target is obliged to see the space
	 * @return a vector. Each element is an array of [id, url, path, label, owner, xmlSpace, read:'T'|'F', write:'T'|'F']
	 * @throws PropertiesException
	 * @throws DataBaseException
	 */
	private Vector getAvailableSpacesForTargets(Vector targetKeys, String targetType, boolean obliged) throws PropertiesException, DataBaseException, ServerException {

		//System.out.println("passe dans getAvailableSpacesForTarget");
		if (log.isDebugEnabled()) {
			log.debug("getAvailableSpacesForTarget :: get spaces for "+targetKeys+" (type="+targetType+")");
		}
		
		// update the database
		Vector dbResult = dbAccess.getAvailableSpacesForTargets(targetKeys, targetType, obliged);
		
		// we check the result
		Vector result = new Vector();
		
		// for each element
		for (int i=0; i<dbResult.size(); i++) {
			
			String[] line = (String[])dbResult.elementAt(i);

			// the xml_server
			String xmlServer = line[1];

			// the from_key
			String fromKey = line[2];

			// the owner
			String ownerKey = line[3];

			// the space root path
			String rootPath = line[4];
			
			if (log.isDebugEnabled()) {
				log.debug("getAvailableSpacesForTarget :: rootPath = "+rootPath);
			}
			
			// the target id
			String idTarget = line[5];

			// the space key
			String spaceKey = line[6];
			
			// get the spaces from the list
			ServerTool tool = new ServerTool(xmlServer);
			ArrayList spaces = tool.getSpaces();
			
			// get the good space
			Space space = null;
			boolean found = false;
			for (int j=0; j<spaces.size() && !found; j++) {
				Space s = (Space)spaces.get(j);
				
				if (s.getKey().equals(spaceKey)) {
					found = true;
					space = s;
				}
			}
			
			// if we found space
			if (space != null) {
				//System.out.println("recupere en base");
				spaces = new ArrayList(1);
				spaces.add(space);
				
				space.getServer().setSpaces(spaces);
				
				// set the owner
				if (ownerKey!=null) {
					if (log.isDebugEnabled()) {
						log.debug("getAvailableSpacesForTarget :: ownerKey = "+ownerKey);
					}
					UserForPersonalization owner = new UserForPersonalization(ownerKey);
					owner.getPersonalization().setReading(1);
					owner.getPersonalization().setWriting(1);
					owner.getPersonalization().setSharing(1);
					owner.getPersonalization().setSecurityRight(true);
					owner.getPersonalization().setModifiable(false);
					space.setOwner(owner);
				}
				else {
					space.setOwner(null);
				}
				
				// construct the shared properties
				SharedSpaceProperties prop = new SharedSpaceProperties();
				//prop.setSharedForUser(targetType.equals(DataBaseAccess.TARGET_IS_USER));
				prop.setFromKey(fromKey);
				
				// the space root path
				prop.setSpaceRootPath(rootPath);
				
				/*if (targetType.equals(DataBaseAccess.TARGET_IS_USER)) {
					if (log.isDebugEnabled()) {
						log.debug("getAvailableSpacesForTarget :: target is user, targetKey = "+targetKey);
					}
					//UserForPersonalization user = new UserForPersonalization(targetKey);
					//prop.setTargetDisplayName(user.getDisplayName());
				}
				else if (targetType.equals(DataBaseAccess.TARGET_IS_GROUP)) {
					//GroupForPersonalization group = new GroupForPersonalization(targetKey, null, false);
					//prop.setTargetDisplayName(group.getDisplayName());
				}
				else {
					//prop.setTargetDisplayName("public");
				}*/

				
				
				
				
				// if is is not public
				if (!targetType.equals(DataBaseAccess.TARGET_IS_ALL)) {
					
					space.setFromConfigFile(false);
					
					if (obliged) {
						space.setPersonnalSpace(false);
						//TODO voir si on doit initialiser enableSharing a cet endroit
						/*if (share.equals("T"))
							space.setEnableSharing("true");
						else space.setEnableSharing("false");*/
					}
					else {
						space.setPersonnalSpace(true);
					}
					
					
					
					
					
					//System.out.println("ici: "+space.getLabel()+" "+prop.getUser());
					space.setCurrentViewer(prop);
					//space.setLogin(userPortalLogin);
					space.setKey(idTarget);
					
					// the server access class
					String serverType = space.getServer().getServerType();
					if (serverType!=null) {
						String serverClass = (String)ChannelConfiguration.getInstance().getServerAccess().get(serverType);
						space.getServer().setServerAccessClass(serverClass);
					}
					
					// the channel action type
					String actionType = space.getActionType();
					if (actionType!=null) {
						String actionClass = (String)ChannelConfiguration.getInstance().getChannelActions().get(actionType);
						space.setChannelActionClass(actionClass);
					}	
					
					// add space to the vector
					result.add(space);
				}
			}
			
			
		}
		
		// return the result
		return result;
	}	
	
	

	/**
	 * Get the available spaces for a user
	 * @param targetKey the key of the target
	 * @param userPortalLogin the login of the user in the portal
	 * @return a vector. Each element is an array of [url, path, label, owner, xmlSpace, read:'T'|'F', write:'T'|'F']
	 * @throws DataBaseException
	 */
	public Vector getAvailableSpacesForUser(String targetKey, boolean obliged) throws DataBaseException, PropertiesException, ServerException {
		//System.out.println("getAvailableSpacesForUser targetKey="+targetKey+", obliged="+obliged);
		Vector targetKeys = new Vector(1);
		targetKeys.addElement(targetKey);
		Vector res = getAvailableSpacesForTargets(targetKeys, DataBaseAccess.TARGET_IS_USER, obliged);
		return res;
	}	


	/**
	 * Get the available spaces for a group
	 * @param targetKey the key of the target
	 * @return a vector. Each element is an array of [url, path, label, owner, xmlSpace, read:'T'|'F', write:'T'|'F']
	 * @throws DataBaseException
	 */
	public Vector getAvailableSpacesForGroups(Vector targetKeys, boolean obliged) throws DataBaseException, PropertiesException, ServerException {
		//System.out.println("getAvailableSpacesForGroups targetKeys="+targetKeys+", obliged="+obliged);
		Vector res = getAvailableSpacesForTargets(targetKeys, DataBaseAccess.TARGET_IS_GROUP, obliged);
		return res;
	}	
	
	/**
	 * Get the available spaces for a group
	 * @param userPortalLogin the login of the portal's user
	 * @param obliged if the user is obliged to see the space
	 * @return a vector. Each element is an array of [url, path, label, owner, xmlSpace, read:'T'|'F', write:'T'|'F']
	 * @throws DataBaseException
	 */
	/*private Vector getAvailableSpacesForAll(boolean obliged) throws DataBaseException, PropertiesException, ServerException {
		//System.out.println("getAvailableSpacesForAll obliged="+obliged);
		Vector targetKeys = new Vector(1);
		targetKeys.addElement(DataBaseAccess.TARGET_ALL);
		Vector res = getAvailableSpacesForTargets(targetKeys, DataBaseAccess.TARGET_IS_ALL, obliged);
		return res;
	}*/
	
	
	
	
	

	/**
	 * Delete a user preference from the database
	 * @param id the id of the sharement in the other database
	 * @param userKey the key of the user
	 * @throws DataBaseException
	 */
	public void delStorageUsersPreferencesForUser(String id, String userKey) throws DataBaseException {

		// set the database
		dbAccess.delStorageUsersPreferencesForUser(id, userKey);
		
	}
	
	

	/**
	 * Delete users preferences for a shared space from the database
	 * @param id the id of the sharement in the other database
	 * @throws DataBaseException
	 */
	public void delStorageUsersPreferences(String id) throws DataBaseException {

		// set the database
		dbAccess.delStorageUsersPreferences(id);
		
	}
	

	

	

	/**
	 * Add a user preference into the database from a user
	 * @param id the id of the sharement in the other database
	 * @param userKey the login of the user in the portal
	 * @param label the label set by the user
	 * @throws DataBaseException
	 */
	public void addStorageUsersPreferences(String id, String userKey, String label) throws DataBaseException {
		
		// set the database
		dbAccess.addStorageUsersPreferences(id, userKey, label);
			
	}

	
	


	/**
	 * Update a user preference label into the database from a user
	 * @param id the id of the sharement in the other database
	 * @param userKey the login of the user in the portal
	 * @param label the label set by the user
	 * @throws DataBaseException
	 */
	public void updateStorageUsersPreferencesLabel(String id, String userKey, String label) throws DataBaseException {
		
		// set the database
		dbAccess.updateStorageUsersPreferencesLabel(id, userKey, label);
			
	}
	

	
	/**
	 * Get the list of ids of spaces which has already been selected by the current user from users table 
	 * @param target the user or group target key
	 * @return a Vector
	 * @throws DataBaseException
	 */
	public Vector[] getKeyOfSpacesFromPreferences(String target) throws DataBaseException {

		// do the request
		Vector[] v = dbAccess.getKeyOfSpacesFromPreferences(target);
		
		// return the result
		return v;
	}
		


	
	
}
