/*
 * Copyright 2004-2014 ICEsoft Technologies Canada Corp.
 *
 * 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.icepush.servlet;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.icepush.Configuration;
import org.icepush.http.ResponseHandler;
import org.icepush.http.Server;
import org.icepush.util.Slot;

public class AsyncAdaptingServlet implements PseudoServlet {
    private final static Logger LOGGER = Logger.getLogger(AsyncAdaptingServlet.class.getName());

    private final Configuration configuration;
    private final Slot heartbeatInterval;
    private final Server server;

    public AsyncAdaptingServlet(final Server server, final Slot heartbeatInterval, final Configuration configuration) {
        this.server = server;
        this.heartbeatInterval = heartbeatInterval;
        this.configuration = configuration;
        LOGGER.log(Level.INFO, "Using Servlet 3.0 AsyncContext");
    }

    public void service(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        if (!request.isAsyncSupported()) {
            throw new EnvironmentAdaptingException();
        }
        server.service(new AsyncRequestResponse(request, response, configuration));
    }

    public void shutdown() {
        server.shutdown();
    }

    private class AsyncRequestResponse extends ServletRequestResponse {
        private final AsyncContext asyncContext;

        public AsyncRequestResponse(
            final HttpServletRequest request, final HttpServletResponse response, final Configuration configuration)
        throws Exception {
            super(request, response, configuration);
            if (request.isAsyncStarted()) {
                asyncContext = request.getAsyncContext();
            } else {
                asyncContext = request.startAsync();
            }
            asyncContext.setTimeout(heartbeatInterval.getLongValue() * 3);
        }

        public void respondWith(final ResponseHandler handler)
        throws Exception {
            try {
                super.respondWith(handler);
            } finally {
                asyncContext.complete();
            }
        }
    }
}
