/*
 *  organization.java
 * 
 *  RELOAD Editor - An IMS Metadata, Content Packaging and Learning Design tool 
 *  with ADAPTATION AT ACTIVITY LEVEL
 *
 *  Copyright (c) 2006 Miguel Fernandez Lores
 *
 *  Technical Contact:
 *  Miguel Fernandez Lores
 *  e-mail: tucias@hotmail.com
 *
 */

package uk.ac.reload.editor.scormadaptive.rules.jdom.rule;

import java.util.List;

import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.filter.Filter;

/**
 * Organization item container class
 *
 * @author  lagar
 * @version 0.2 
 */
public class organization { 
    
    private String sIDRef;
    private String sTitle;
    private Element referencedOrganization;
    
    /** Creates a new instance of item */
    public organization(String ref) {
        sIDRef = ref;
        sTitle = "---";
    }
    
    public organization(Element oEl) throws Exception{
        Attribute oAtt = oEl.getAttribute("IDRef");
        if (oAtt == null) {
             throw new Exception("Organization: Attribute IDRef is mandatory");
        }
        else sIDRef = oAtt.getValue();

        Element oRoot = oEl.getDocument().getRootElement();
        referencedOrganization = null;
        // tras esta llamada queda en referencedOrganization el organization referenciado por IDRef
        searchReferenced(oRoot);
        if (referencedOrganization != null) {
        	Element title = referencedOrganization.getChild("title", referencedOrganization.getNamespace());      	
        	if (title != null) sTitle = title.getTextTrim();        		        	
        }

        //System.out.println("sTitle: " + sTitle);        
    }
    
    
    private void searchReferenced(Element father) {

    	Filter filter = new Filter() {
        	public boolean matches(Object elem) {
        		if (elem.getClass() == Element.class) return true;
        		else return false;        		
        	}
        };
        List hijos = father.getContent(filter);
        
        for (int i = 0; i < hijos.size(); i++) {
        	if (((Element)hijos.get(i)).getAttribute("identifier") != null) {
        		if  (((Element)hijos.get(i)).getAttribute("identifier").getValue().equals(sIDRef)) referencedOrganization = (Element) hijos.get(i);        	        		
        	}
        	if (((Element)hijos.get(i)).getChildren().size() > 0) searchReferenced((Element)hijos.get(i));
        }   	
    }
    
    public String getID(){
        return sIDRef;
    
    }
    
    public String getTitle(){
        return sTitle;
    }
    
}
