/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/report/PrincipalPropertySearchReport.java,v 1.10 2004/08/05 14:43:34 dflorey Exp $
 * $Revision: 1.10 $
 * $Date: 2004/08/05 14:43:34 $
 *
 * ====================================================================
 *
 * 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.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.RequestedProperty;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.SlideException;
import org.apache.slide.common.SlideToken;
import org.apache.slide.content.NodeRevisionNumber;
import org.apache.slide.search.RequestedResource;
import org.apache.slide.search.SearchQuery;
import org.apache.slide.search.basic.Literals;
import org.apache.slide.structure.SubjectNode;
import org.apache.slide.webdav.WebdavServletConfig;
import org.apache.slide.webdav.util.AclConstants;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.ViolatedPrecondition;
import org.apache.slide.webdav.util.WebdavStatus;
import org.apache.slide.webdav.util.WebdavUtils;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.XMLOutputter;

/**
 * DAV:principal-property-search report worker.
 *
 */
public class PrincipalPropertySearchReport extends AbstractReport implements AclConstants {
    
    private RequestedProperties requestedProperties = null;
    private List conditionList = null;
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    servletPath         a String, the result of HttpRequest.getServletPath()
     * @param    contextPath         a  String , the result of HttpRequest.getContextPath()
     */
    public PrincipalPropertySearchReport(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    principalPropertySearchElm   an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element principalPropertySearchElm) throws PreconditionViolationException {
        if (principalPropertySearchElm.getChildren().size() == 0) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-least-one-child-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:principal-property-search element must have at least one child"),
                resourcePath
            );
        }
        List propertySearchElmL = principalPropertySearchElm.getChildren(E_PROPERTY_SEARCH, DNSP);
        if (propertySearchElmL.size() == 0) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-least-one-property-search-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:principal-property-search element must contain at least one DAV:property-search element"),
                resourcePath
            );
        }
        Iterator ps = propertySearchElmL.iterator();
        this.conditionList = new ArrayList();
        while (ps.hasNext()) {
            Element propertySearchElm = (Element)ps.next();
            Element matchElm = propertySearchElm.getChild(E_MATCH, DNSP);
            if (matchElm == null) {
                continue;
            }
            Element propElm = propertySearchElm.getChild(E_PROP, DNSP);
            Iterator pElms = propElm.getChildren().iterator();
            while (pElms.hasNext()) {
                Element pElm = (Element)pElms.next();
                Element newpropElm = new Element(E_PROP, DNSP);
                newpropElm.addContent(new Element(pElm.getName(), pElm.getNamespace()));
                Element propcontainsElm = new Element("propcontains", Namespace.getNamespace("http://jakarta.apache.org/slide/"));
                Element literalElm = new Element(Literals.LITERAL, DNSP);
                literalElm.addContent(matchElm.getTextTrim());
                propcontainsElm.addContent(newpropElm);
                propcontainsElm.addContent(literalElm);
                conditionList.add(propcontainsElm);
            }
        }
        List propElmL = principalPropertySearchElm.getChildren(E_PROP, DNSP);
        if (propElmL.size() > 1) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-most-one-prop-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:principal-property-search element must have at most one DAV:prop child"),
                resourcePath
            );
        }
        
        if (propElmL.size() == 1) {
            Element propElm = (Element)propElmL.get(0);
            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 {
        SubjectNode currentUserNode = (SubjectNode)security.getPrincipal(slideToken);
        Element queryElm = getQueryElement(resourcePath, currentUserNode);
        new XMLOutputter(org.jdom.output.Format.getPrettyFormat()).output(queryElm, System.out);
        
        String absUri = WebdavUtils.getAbsolutePath (resourcePath, slideContextPath, config);
        
        SearchQuery query =
            search.createSearchQuery(queryElm.getNamespaceURI(),
                                     queryElm,
                                     slideToken,
                                     config.getDepthLimit(),
                                     absUri);
        
        Iterator result = query.execute().iterator();
        while (result.hasNext()) {
            RequestedResource r = (RequestedResource)result.next();
            multistatusElm.addContent(getResponseElement(slideToken, r.getUri(), new NodeRevisionNumber(), requestedProperties));
        }
        
    }
    
    private Element getQueryElement(String resourcePath, SubjectNode currentUserNode) {
        Element result = new Element(Literals.BASICSEARCH, DNSP);
        // select
        Element selectElm = new Element(Literals.SELECT, DNSP);
        result.addContent(selectElm);
        Element propElm = new Element(E_PROP, DNSP);
        selectElm.addContent(propElm);
        Iterator props = requestedProperties.getRequestedProperties();
        while (props.hasNext()) {
            RequestedProperty p = (RequestedProperty)props.next();
            Namespace nsp = (DNSP.getURI().equals(p.getNamespace()))
                ? DNSP
                : Namespace.getNamespace(p.getNamespace());
            propElm.addContent(new Element(p.getName(), nsp));
        }
        // from
        Element fromElm = new Element(Literals.FROM, DNSP);
        result.addContent(fromElm);
        Element scopeElm = new Element(Literals.SCOPE, DNSP);
        fromElm.addContent(scopeElm);
        Element hrefElm = new Element(E_HREF, DNSP);
        hrefElm.setText(WebdavUtils.getAbsolutePath (resourcePath, slideContextPath, config));
        
        scopeElm.addContent(hrefElm);
        // where
        if (conditionList.size() > 0) {
            Element whereElm = new Element(Literals.WHERE, DNSP);
            result.addContent(whereElm);
            if (conditionList.size() == 1) {
                whereElm.addContent((Element)conditionList.get(0));
            }
            else {
                Element andElm = new Element(Literals.AND, DNSP);
                whereElm.addContent(andElm);
                Iterator conditions = conditionList.iterator();
                while (conditions.hasNext()) {
                    andElm.addContent((Element)conditions.next());
                }
            }
        }
        return result;
    }
    
    /**
     * Method checkPreconditions
     * @param    resourcePath        a  String
     * @param    depth               an int
     * @throws   PreconditionViolationException
     * @throws   ServiceAccessException
     */
    public void checkPreconditions(String resourcePath, int depth) throws PreconditionViolationException, ServiceAccessException {
        if (depth != 0) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("depth-must-be-zero",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "This report is only defined for depth=0."),
                resourcePath
            );
        }
    }
}
