/**
 * Created on Jun 18, 2005
 * $id:  $
 */
package org.jvnet.lookout.ui.core.tree;

import java.io.Serializable;

import org.jvnet.lookout.core.model.SearchResultProperty;


public class SearchResultItem extends TreeParent implements Serializable {
    
    public SearchResultItem() {
        super();
    }
    public SearchResultItem(String name) {
        super(name);
    }
    
    /**
     * Will return null if no SearchResultDetail matches the SearchResultProperty specified.
     * 
     * @param property
     * @return
     */
    public SearchResultDetail getDetail(SearchResultProperty property) {
        
        if(property != null) {
            for (int i = 0; i < getChildren().length; i++) {
            	
            	TreeObject treeObject = getChildren()[i];
            	
            	if(treeObject instanceof SearchResultDetail) {
            		SearchResultDetail detail = (SearchResultDetail)(treeObject);
            		if(property.equals(detail.getProperty())) {
            			return detail;
            		}            
            	}
            }
        }
        return null;
    }
    
    public boolean hasPropertyValue(SearchResultProperty property) {
        return null == getDetail(property);                
    }

    public Object getPropertyValue(SearchResultProperty property) {
        SearchResultDetail detail = getDetail(property);        
        return (null != detail) ? detail.getValue() : null;
    }

    public void setPropertyValue(SearchResultProperty property, Object value, boolean createIfNeeded) {
        
        SearchResultDetail detail = getDetail(property);        
        
        if ((null == detail) && (createIfNeeded)) {
                detail = new SearchResultDetail();    
                detail.setProperty(property);
                detail.setValue(value);
                addChild(detail);
        } else if (null != detail){
            detail.setValue(value);
        }
    }
    @Override
    public String toString() {

        Object value = getPropertyValue(SearchResultProperty.NAME);
        if(null == value) {
            return super.toString();
        } else {
            return value.toString();
        }
    }
}
