//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   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 de.ugoe.cs.autoquest.httpmonitor.proxy;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;

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

import de.ugoe.cs.autoquest.httpmonitor.HttpMonitorComponent;
import de.ugoe.cs.autoquest.httpmonitor.HttpMonitorException;
import de.ugoe.cs.autoquest.httpmonitor.HttpMonitorExchangeHandler;
import de.ugoe.cs.autoquest.httpmonitor.exchange.Status;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * {@link ExchangeListener}s need to be managed, as there is one instantiated for each proxied
 * request/response. They need to be timed out, if for a longer time, no update is received. All
 * this is done by the ExchangeListenerManager.
 * </p>
 * 
 * @author Patrick Harms
 */
class ExchangeListenerManager implements HttpMonitorComponent {

    /**
     * <p>
     * the timeout after which a writer of an inactive client is closed
     * </p>
     */
    private static final int SESSION_TIMEOUT = 10 * 60 * 1000;
    
    /**
     * <p>
     * the exchange handler forwarded to the exchange listeners
     * </p>
     */
    private HttpMonitorExchangeHandler exchangeHandler;
    
    /**
     * <p>
     * the mapping of requests handled by the proxy to the respective exchange listeners
     * </p>
     */
    private Map<HttpServletRequest, ExchangeListener> listeners;

    /**
     * <p>
     * a timer used to detect exchange listener timeouts
     * </p>
     */
    private Timer listenerTimer;

    /**
     * <p>
     * creates the exchange listener manager with the exchange handler to be forwarded to the
     * exchange listeners
     * </p>
     * 
     * @param exchangeHandler the exchange handler to be forwarded to the exchange listeners
     */
    ExchangeListenerManager(HttpMonitorExchangeHandler exchangeHandler) {
        this.exchangeHandler = exchangeHandler;
    }

    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#init()
     */
    @Override
    public synchronized void init() throws IllegalStateException, HttpMonitorException {
        Console.traceln(Level.FINER, "initializing exchange listener manager");
        
        if (listeners != null) {
            throw new IllegalStateException("already initialized");
        }
        
        listeners = new HashMap<HttpServletRequest, ExchangeListener>();
        listenerTimer = new Timer();
    }

    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#start()
     */
    @Override
    public synchronized void start() throws IllegalStateException, HttpMonitorException {
        Console.traceln(Level.FINER, "starting exchange listener manager");

        if (listeners == null) {
            throw new IllegalStateException("not initialized");
        }
        
        listenerTimer.schedule
            (new ListenerMonitorTimerTask(), SESSION_TIMEOUT / 2, SESSION_TIMEOUT / 2);
    }

    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#stop()
     */
    @Override
    public synchronized void stop() {
        Console.traceln(Level.FINER, "stopping exchange listener manager");

        if (listenerTimer != null) {
            listenerTimer.cancel();
        }
        
        if (listeners != null) {
            for (ExchangeListener listener : listeners.values()) {
                listener.onFinish(Status.TIMEOUT);
            }
        }
        
        listeners = null;
    }

    /**
     * <p>
     * called, when the request was received by the proxy. Calls the appropriate method on
     * the exchange listener.
     * </p>
     * 
     * @param request the request of the exchange
     */
    public void onRequest(HttpServletRequest request) throws IllegalStateException {
        ensureListener(request).onRequest(request);
    }

    /**
     * <p>
     * called, when some content of the request was processed by the proxy. Calls the appropriate
     * method on the exchange listener.
     * </p>
     * 
     * @param request the request of the exchange
     * @param data    the processed content of the request of the exchange
     */
    public void onRequestContent(HttpServletRequest request, ByteBuffer data)
        throws IllegalStateException
    {
        ensureListener(request).onRequestContent(data);
    }

    /**
     * <p>
     * called, when the response is to be returned by the proxy. Calls the appropriate
     * method on the exchange listener.
     * </p>
     * 
     * @param request  the request of the exchange
     * @param response the response of the exchange
     */
    public void onResponse(HttpServletRequest request, HttpServletResponse response)
        throws IllegalStateException
    {
        ensureListener(request).onResponse(response);
    }

    /**
     * <p>
     * called, when some content of the response was processed by the proxy. Calls the appropriate
     * method on the exchange listener.
     * </p>
     * 
     * @param request the request of the exchange
     * @param data    the processed content of the response of the exchange
     */
    public void onResponseContent(HttpServletRequest request, ByteBuffer data)
        throws IllegalStateException
    {
        ensureListener(request).onResponseContent(data);
    }

    /**
     * <p>
     * called, when proxy finished proxying a request. Calls the appropriate method on the
     * exchange listener and afterwards cleans up the listener.
     * </p>
     * 
     * @param request the request of the exchange
     * @param status  the status of the proxying after finalization
     */
    public void onFinish(HttpServletRequest request, Status status) throws IllegalStateException {
        ensureListener(request).onFinish(status);
        Console.traceln(Level.FINEST, "removing exchange listener for " + request);
        listeners.remove(request);
    }

    /**
     * <p>
     * convenience method to ensure a listener for a specific HTTP servlet request to be handled.
     * </p>
     */
    private ExchangeListener ensureListener(HttpServletRequest request) {
        ExchangeListener listener = listeners.get(request);
        
        if (listener == null) {
            synchronized (this) {
                listener = listeners.get(request);
                if (listener == null) {
                    Console.traceln(Level.FINEST, "creating exchange listener for " + request);
                    listener = new ExchangeListener(exchangeHandler); 
                    listeners.put(request, listener);
                }
            }
        }

        return listener;
    }

    /**
     * <p>
     * internal timer task used for detecting exchange timeouts
     * </p>
     * 
     * @author Patrick Harms
     */
    public class ListenerMonitorTimerTask extends TimerTask {

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            synchronized (ExchangeListenerManager.this) {
                List<HttpServletRequest> timeoutRequests = new ArrayList<HttpServletRequest>();
                for (Map.Entry<HttpServletRequest, ExchangeListener> entry : listeners.entrySet()) {
                    ExchangeListener listener = entry.getValue();
                    
                    if (System.currentTimeMillis() - listener.getLastUpdate() > SESSION_TIMEOUT) {
                        timeoutRequests.add(entry.getKey());
                    }
                }
                
                for (HttpServletRequest request : timeoutRequests) {
                    ExchangeListener listener = listeners.remove(request);
                    listener.onFinish(Status.TIMEOUT);
                }
            }
        }

    }

}
