/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/report/XLocateByHistoryReport.java,v 1.1 2004/09/15 14:58:25 pnever Exp $
 * $Revision: 1.1 $
 * $Date: 2004/09/15 14:58:25 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 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.store.tamino.report;

import org.apache.slide.common.*;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.webdav.WebdavServletConfig;
import org.apache.slide.webdav.method.report.LocateByHistoryReport;
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;
import org.jdom.output.XMLOutputter;


/**
 * Query-based report implementation.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.1 $
 */

public final class XLocateByHistoryReport extends LocateByHistoryReport implements DeltavConstants {
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public XLocateByHistoryReport(SlideToken slideToken, NamespaceAccessToken token, WebdavServletConfig config, String slideContextPath) {
        super(slideToken, token, config, slideContextPath);
    }
    
    /**
     * 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;
        }
        Element queryElm = getQueryElement(resourcePath);
//        new XMLOutputter("  ", true).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) {
        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
        List vhrUris = versionHistorySet.getHrefStrings();
        if (vhrUris.size() > 0) {
            Element whereElm = new Element(Literals.WHERE, DNSP);
            result.addContent(whereElm);
            if (vhrUris.size() == 1) {
                String vhrUri = (String)vhrUris.get(0);
                Element eqElm = new Element(Literals.EQ, DNSP);
                whereElm.addContent(eqElm);
                propElm = new Element(Literals.PROP, DNSP);
                Element literalElm = new Element(Literals.LITERAL, DNSP);
                eqElm.addContent(propElm);
                eqElm.addContent(literalElm);
                propElm.addContent(new Element(P_VERSION_HISTORY, DNSP));
                String literal = vhrUri;
                if (literal.startsWith(slideContextPath)) {
                    UriPath up = new UriPath(literal);
                    literal = up.subUriPath(1, up.tokens().length).toString();
                }
                literalElm.addContent(literal);
            }
            else {
                Iterator iterator = vhrUris.iterator();
                while (iterator.hasNext()) {
                    String vhrUri = (String)iterator.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
        //            );
        //        }
    }
}


