/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/SubscribeMethod.java,v 1.13 2005/02/25 17:03:53 luetzkendorf Exp $
 * $Revision: 1.13 $
 * $Date: 2005/02/25 17:03:53 $
 *
 * ====================================================================
 *
 * Copyright 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.webdav.method;

import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.event.EventDispatcher;
import org.apache.slide.webdav.WebdavException;
import org.apache.slide.webdav.WebdavServletConfig;
import org.apache.slide.webdav.event.NotificationTrigger;
import org.apache.slide.webdav.event.Subscriber;
import org.apache.slide.webdav.event.WebdavEvent;
import org.apache.slide.webdav.util.NotificationConstants;
import org.apache.slide.webdav.util.WebdavStatus;


/**
 * Subscribe Method.
 *
 */
public class SubscribeMethod extends AbstractWebdavMethod implements NotificationConstants {
    protected static final String LOG_CHANNEL = SubscribeMethod.class.getName();

    private final static int DEFAULT_SUBSCRIPTION_LIFETIME = 3600;

    /**
     * Constructor.
     *
     * @param token     the token for accessing the namespace
     * @param config    configuration of the WebDAV servlet
     */
    public SubscribeMethod(NamespaceAccessToken token,
                         WebdavServletConfig config) {
        super(token, config);
    }
    
    protected void parseRequest() throws WebdavException {
    }
    
    protected void executeRequest() throws WebdavException {
        try {
            if ( WebdavEvent.SUBSCRIBE.isEnabled() ) EventDispatcher.getInstance().fireVetoableEvent(WebdavEvent.SUBSCRIBE, new WebdavEvent(this));
            String callback = requestHeaders.getCallback();
            String notificationType = requestHeaders.getNotificationType();
            int notificationDelay = requestHeaders.getNotificationDelay(0);
            int subscriptionLifetime = requestHeaders.getSubscriptionLifetime(DEFAULT_SUBSCRIPTION_LIFETIME);
            int depth = requestHeaders.getDepth(INFINITY);
            int []subscriptionIDs = requestHeaders.getSubscriptionId();
            
            if ( subscriptionIDs.length > 0 ) {
                // renew subscribers
                for ( int i = 0; i < subscriptionIDs.length; i++ ) {
                    Subscriber subscriber = NotificationTrigger.getInstance().getSubscriber(subscriptionIDs[i]);
                    if ( subscriber != null ) {
                        NotificationTrigger.getInstance().refreshSubscriber(subscriber, true);
                    }
                }
            } else {
                if (notificationType == null) {
                   sendError(WebdavStatus.SC_BAD_REQUEST, "Notification-Type header missing.");
                   return;
                } else {
                   // FIXME check for valid notification types
                }
                Subscriber subscriber = new Subscriber(requestUri, callback, notificationType, notificationDelay, 
                      subscriptionLifetime, depth);
                int subscriptionID = NotificationTrigger.getInstance().addSubscriber(subscriber);
                resp.setHeader(H_CALL_BACK, callback);
                resp.setHeader(H_NOTIFICATION_TYPE, notificationType);
                resp.setHeader(H_SUBSCRIPTION_LIFETIME, String.valueOf(subscriptionLifetime));
                resp.setHeader(H_SUBSCRIPTION_ID, String.valueOf(subscriptionID));
                resp.setHeader(H_CONTENT_LOCATION, 
                      getSlideContextPath() + requestUri);
                resp.setStatus(WebdavStatus.SC_OK);
            }
        } catch (Exception e) {
            int statusCode = getErrorCode(e);
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
    }
}