/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/report/ExpandPropertyReport.java,v 1.5 2004/07/28 09:32:12 ib Exp $
 * $Revision: 1.5 $
 * $Date: 2004/07/28 09:32:12 $
 *
 * ====================================================================
 *
 * Copyright 1999-2002 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.slide.webdav.method.report;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.common.PropertyParseException;
import org.apache.slide.common.RequestedProperties;
import org.apache.slide.common.RequestedPropertiesImpl;
import org.apache.slide.common.SlideException;
import org.apache.slide.common.SlideToken;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.NodeRevisionDescriptors;
import org.apache.slide.structure.ObjectNode;
import org.apache.slide.webdav.WebdavServletConfig;
import org.apache.slide.webdav.util.DeltavConstants;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.WebdavUtils;
import org.jdom.Element;
import org.jdom.Namespace;


/**
 * DAV:expand-property report worker.
 *
 */
public class ExpandPropertyReport extends AbstractReport implements DeltavConstants {
    
    private static final String PROPERTY_LIST = "propertylist";
    
    private List propertyElmList;
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public ExpandPropertyReport(SlideToken slideToken, NamespaceAccessToken token, WebdavServletConfig config, String slideContextPath) {
        super(slideToken, token, config, slideContextPath);
    }
    
    /**
     * Initialize report worker with specified report element
     *
     * @param    resourcePath        a  String
     * @param    expandPropertyElm   an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element expandPropertyElm) throws PreconditionViolationException {
        this.propertyElmList = expandPropertyElm.getChildren(E_PROPERTY, DNSP);
    }
    
    /**
     * Execute report and add results to given multistatus element
     *
     * @param    resourcePath        a  String
     * @param    multistatusElm      an Element
     * @param    depth               an int
     *
     * @throws   SlideException
     * @throws   IOException
     */
    public void execute(String resourcePath, Element multistatusElm, int depth) throws SlideException, IOException {
        if (depth < 0) {
            return;
        }
        writeReport( resourcePath, multistatusElm, propertyElmList );
        ObjectNode onode = structure.retrieve( slideToken, resourcePath );
        Enumeration childrenEnum = structure.getChildren( slideToken, onode );
        while( childrenEnum.hasMoreElements() ) {
            ObjectNode cnode = (ObjectNode)childrenEnum.nextElement();
            execute(cnode.getUri(), multistatusElm, depth-1);
        }
    }
    
    private void writeReport(String resourcePath, Element multistatusElm, List propertyElmList) {
        
        try {
            NodeRevisionDescriptors nrds = content.retrieve(slideToken, resourcePath);
            NodeRevisionDescriptor nrd = content.retrieve(slideToken, nrds);
            
            Element response = getResponseElement(slideToken,
                                                  resourcePath,
                                                  nrd.getRevisionNumber(),
                                                  createRequestedProperties(propertyElmList));
            
            multistatusElm.addContent(response);
            
            // check for nested <property> elements
            Iterator iterator = propertyElmList.iterator();
            while (iterator.hasNext()) {
                Element propertyElement = (Element)iterator.next();
                List childPropertyList = propertyElement.getChildren();
                if (childPropertyList.size() > 0) {
                    try {
                        Namespace propertyNamespace = DNSP;
                        String propertyNamespaceStr = propertyElement.getAttributeValue("namespace");
                        if( propertyNamespaceStr != null )
                            propertyNamespace = Namespace.getNamespace(propertyNamespaceStr);
                        List hrefElements = response.
                            getChild(E_PROPSTAT, DNSP).
                            getChild(E_PROP, DNSP).
                            getChild(propertyElement.getAttribute("name").getValue(), propertyNamespace).
                            getChildren(E_HREF, DNSP);
                        Iterator hrefs = new ArrayList(hrefElements).iterator();
                        while( hrefs.hasNext() ) {
                            Element hrefElement = (Element)hrefs.next();
                            if (hrefElement.getText() != null) {
                                // replace the <href> with <response> of the corresponding resource
                                writeReport(
                                    WebdavUtils.getSlidePath(hrefElement.getTextTrim(),
                                                             slideContextPath),
                                               (Element)hrefElement.getParent(),
                                    childPropertyList);
                                hrefElement.getParent().removeContent(hrefElement);
                            }
                        }
                    }
                    catch (NullPointerException e) {
                        // there is no such <href> element, so what..?
                    }
                }
            }
        }
        catch (Exception e) {
            multistatusElm.addContent(getErrorResponse(resourcePath, WebdavUtils.getErrorCode(e), null));
        }
    }
    
    private RequestedProperties createRequestedProperties(List propertyElements) throws PropertyParseException {
        
        Element propertyListElement = new Element(PROPERTY_LIST);
        Iterator iterator = propertyElements.iterator();
        while (iterator.hasNext()) {
            propertyListElement.addContent((Element)((Element)iterator.next()).clone());
        }
        return new RequestedPropertiesImpl(propertyListElement);
    }
}

