/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/report/LocateByHistoryReport.java,v 1.9 2004/12/21 16:04:20 luetzkendorf Exp $
 * $Revision: 1.9 $
 * $Date: 2004/12/21 16:04:20 $
 *
 * ====================================================================
 *
 * 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.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.NodeProperty;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.NodeRevisionDescriptors;
import org.apache.slide.structure.ObjectNode;
import org.apache.slide.util.XMLValue;
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.UriHandler;
import org.apache.slide.webdav.util.ViolatedPrecondition;
import org.apache.slide.webdav.util.WebdavStatus;
import org.apache.slide.webdav.util.WebdavUtils;
import org.apache.slide.webdav.util.resourcekind.AbstractResourceKind;
import org.apache.slide.webdav.util.resourcekind.ResourceKind;
import org.apache.slide.webdav.util.resourcekind.VersionControlled;
import org.jdom.Element;
import org.jdom.JDOMException;


/**
 * DAV:locate-by-history report worker.
 *
 */
public class LocateByHistoryReport extends AbstractReport implements DeltavConstants {
    
    protected RequestedProperties requestedProperties = null;
    protected XMLValue versionHistorySet = null;
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public LocateByHistoryReport(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    versionTreeElm      an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element locateByHistoryElm) throws PreconditionViolationException {
        List childrenList = locateByHistoryElm.getChildren();
        if (childrenList.size() != 2) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("invalid-locate-by-history",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:locate-by-history element must have 2 children: DAV:version-history-set and DAV:prop"),
                resourcePath
            );
        }
        
        Element versionHistorySetElm = null;
        Element propElm = null;
        if ( E_VERSION_HISTORY_SET.equals(((Element)childrenList.get(0)).getName()) &&
            E_PROP.equals(((Element)childrenList.get(1)).getName()) ) {
            versionHistorySetElm = (Element)childrenList.get(0);
            propElm = (Element)childrenList.get(1);
        }
        else if ( E_PROP.equals(((Element)childrenList.get(0)).getName()) &&
                 E_VERSION_HISTORY_SET.equals(((Element)childrenList.get(1)).getName()) ) {
            propElm = (Element)childrenList.get(0);
            versionHistorySetElm = (Element)childrenList.get(1);
        }
        else {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("invalid-locate-by-history",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:locate-by-history element must have 2 children: DAV:version-history-set and DAV:prop"),
                resourcePath
            );
        }
        
        // <locate-by-history> report can only be applied to collection
        if ( ! WebdavUtils.isCollection(token, slideToken, resourcePath) ) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("must-be-collection",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "the request-URI must specify a collection"),
                resourcePath
            );
        }
        
        this.versionHistorySet =
            new XMLValue(versionHistorySetElm.getChildren(E_HREF, DNSP));
        
        // check DAV:must-be-version-history
        UriHandler uriHandler = null;
        String href = null;
        boolean isVersionHistory = false;
        Iterator iterator = versionHistorySet.getHrefStrings().iterator();
        while (iterator.hasNext()) {
            href = (String)iterator.next();
            uriHandler = UriHandler.getUriHandler(WebdavUtils.getSlidePath(href, slideContextPath));
            isVersionHistory = uriHandler.isHistoryUri();
            if (!isVersionHistory) {
                break;
            }
        }
        if (!isVersionHistory) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition(C_MUST_BE_VERSION_HISTORY,
                                         WebdavStatus.SC_CONFLICT),
                resourcePath
            );
        }
        
        try {
            this.requestedProperties = new RequestedPropertiesImpl(propElm);
        }
        catch (PropertyParseException e) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("invalid-prop",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         e.getMessage()),
                resourcePath
            );
        }
    }
    
    /**
     * 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;
        }
        
        NodeRevisionDescriptor nrd = null;
        NodeRevisionDescriptors nrds = null;
        ResourceKind resourceKind = null;
        String versionHistoryUri = null;
        ObjectNode collectionNode = structure.retrieve(slideToken, resourcePath);
        Enumeration children = structure.getChildren(slideToken, collectionNode);
        while (children.hasMoreElements()) {
            
            ObjectNode child = (ObjectNode)children.nextElement();
            if (child.hasChildren()) {
                execute(child.getUri(), multistatusElm, depth-1);
            }
            else {
                nrds = content.retrieve(slideToken, child.getUri());
                nrd = content.retrieve(slideToken, nrds);
                resourceKind = AbstractResourceKind.determineResourceKind(token, child.getUri(), nrd);
                versionHistoryUri = null;
                
                if (resourceKind instanceof VersionControlled) {
                    versionHistoryUri = getHistoryUriOfVCR(nrd);
                }
                
                if (versionHistoryUri != null) {
                    boolean found = false;
                    Iterator iterator = versionHistorySet.iterator();
                    String currentHistoryUri = null;
                    while ( !found && iterator.hasNext() ) {
                        currentHistoryUri = ((Element)iterator.next()).getText();
                        if (currentHistoryUri != null) {
                            currentHistoryUri = WebdavUtils.getSlidePath(currentHistoryUri, slideContextPath);
                        }
                        found = versionHistoryUri.equals(currentHistoryUri);
                    }
                    if (found) {
                        multistatusElm.addContent(getResponseElement(slideToken, child.getUri(), nrd.getRevisionNumber(), requestedProperties));
                    }
                }
            }
        }
    }
    
    private String getHistoryUriOfVCR(NodeRevisionDescriptor revisionDescriptor) {
        
        String historyUri = null;
        NodeProperty property = revisionDescriptor.getProperty(PN_CHECKED_IN);
        if (property == null) {
            property = revisionDescriptor.getProperty(PN_CHECKED_OUT);
        }
        if ( (property != null) && (property.getValue() != null) ) {
            try {
                XMLValue xmlValue = new XMLValue(property.getValue().toString());
                Iterator iterator = xmlValue.iterator();
                if (iterator.hasNext()) {
                    String vrUri = ((Element)iterator.next()).getText();
                    UriHandler uriHandler = UriHandler.getUriHandler(vrUri);
                    if (uriHandler.isVersionUri()) {
                        historyUri = uriHandler.getAssociatedHistoryUri();
                    }
                }
            }
            catch (JDOMException e) {}
        }
        
        return historyUri;
    }
}

