/*
 * Created on 18 oct. 06
 */
package org.esupportail.portal.channels.CStockage.channelAction.groupManager;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * Id: UserGroupTree.java,v 1.0 18 oct. 06
 * Copyright (c) 2005 Esup Portail (www.esup-portail.org)
 * Classes: UserGroupTree
 * Original Author: Yohan Colmant
 * 
 */
public class UserGroupTree {

	private Hashtable groupsState;
	private GroupTreeEntry groupTreeEntry; 
	private String spaceKey;
	
	
	public UserGroupTree(String spaceKey, String rootPath) {
		this.groupsState = new Hashtable();
		this.spaceKey = spaceKey;
		
		this.groupTreeEntry = GroupTree.initRootGroupEntry(spaceKey, rootPath);
	}
	
	
	/**
	 * @return true if the root group entry is initialized
	 */
	public boolean isRootGroupEntryInitialized() {
		if (this.groupTreeEntry==null) {
			this.groupTreeEntry = GroupTree.getRootGroupEntry(spaceKey);
		}
		
		return this.groupTreeEntry!=null;
	}
	
	
	
	
	
	/**
	 * @return the root group entry
	 */
	public GroupTreeEntry getRootGroupEntry() {
		return groupTreeEntry;
	}
	
	
	
	/**
	 * @return the group entry
	 */
	private GroupTreeEntry getGroupEntry(String id, GroupTreeEntry entry) {
		
		if (entry.getId().equals(id)) {
			return entry;
		}
		else {
			if (entry.getChildren()!=null) {
				Iterator iter = entry.getChildren().iterator();
				while (iter.hasNext()) {
					GroupTreeEntry gte = (GroupTreeEntry)iter.next();
					GroupTreeEntry result = getGroupEntry(id, gte);
					if (result != null) {
						return result;
					}
				}
			}
		}
		return null;
	}
	
	/**
	 * @return the group entry
	 */
	public GroupTreeEntry getGroupEntry(String id) {
		return getGroupEntry(id, this.groupTreeEntry);
	}
	
	
	/**
	 * @return true if this id exists
	 */
	public boolean existGroupEntryId(String id) {
		return getGroupEntry(id, this.groupTreeEntry)!=null;
	}
	
	
	/**
	 * @param open the open to set
	 */
	public void setOpen(String id, boolean open) {
		UserGroupTreeState ugts = (UserGroupTreeState)groupsState.get(id);
		if (ugts == null) {
			ugts = new UserGroupTreeState(open);
			groupsState.put(id, ugts);
		}
		else {
			ugts.setOpen(open);
		}
	}
	
	
	/**
	 * @param open the open to set
	 */
	public boolean isOpen(String id) {
		UserGroupTreeState ugts = (UserGroupTreeState)groupsState.get(id);
		if (ugts == null) {
			ugts = new UserGroupTreeState(false);
			groupsState.put(id, ugts);
		}
		return ugts.isOpen();
	}
	
	
}
