/*
 * Copyright (C) 2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.cms.dispatcher;

import com.arsdigita.templating.PatternGenerator;
import com.arsdigita.templating.PatternStylesheetResolver;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;

/**
 *  This looks to see if there is a given item and if there is it returns
 *  the oid for that item as the gererated value
 */
public class ItemDelegatedURLPatternGenerator implements PatternGenerator {
    // this is used to prevent an infinite loop where this stylesheet
    // always matches.  If we did not use then then the call to 
    // the PatternStylesheetResolver would cause the loop
    private static final String DELEGATED_ALREADY_GENERATED = 
        "delegatedAlreadyGenerated";

    public String[] generateValues(String key,
                                   HttpServletRequest req) {
        if (req.getAttribute(DELEGATED_ALREADY_GENERATED) == null) {
            // this has to be before the call to delegator.resolver otherwise
            // we end up in an infinite loop
            req.setAttribute(DELEGATED_ALREADY_GENERATED, Boolean.TRUE);
            PatternStylesheetResolver delegator = 
                new PatternStylesheetResolver();
            URL delegated = delegator.resolve(req);
            
            String[] del = new String[1];
            del[0] = delegated.toString();
            return del;
        } else {
            return new String[] {};
        }
    }
}
