/*
 This file is part of GNUnet.
 (C) 2014 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 */

package org.gnunet.requests;

import org.gnunet.mq.MessageQueue;

import java.util.LinkedList;

/**
 * Container for requests that are responded to in sequential order.
 */
public class SequentialRequestContainer<T extends Request> extends RequestContainer {
    /**
     * Allow overlapping requests.
     */
    private boolean overlap;
    /**
     * Request in our queue with information about them.
     */
    private LinkedList<Identifier> requests = new LinkedList<Identifier>();
    /**
     * Message queue that is used to send envelopes.
     */
    private final MessageQueue mq;

    /**
     * Number of active requests.
     */
    private int requestsActive = 0;

    /**
     * Create a sequential request container that sends messages with the given
     * message queue.
     *
     * @param mq message queue to send messages with
     * @param overlap allow sending requests while other request have not yet completed
     */
    public SequentialRequestContainer(MessageQueue mq, boolean overlap) {
        this.mq = mq;
        this.overlap = overlap;
    }
    /**
     * Create a sequential request container that sends messages with the given
     * message queue.  Do not allow other requests to be send while the current request
     * is still active.
     *
     * @param mq message queue to send messages with
     */
    public SequentialRequestContainer(MessageQueue mq) {
       this(mq, false);
    }
    /**
     * Get the current request's identifier.
     *
     * @return current request
     */
    public RequestIdentifier<T> getRequestIdentifier() {
        return requests.peekFirst();
    }

    /**
     * Get the current request and retire it.
     * If there is no current request, null will be returned.
     *
     * @return current request
     */
    public T getAndRetireRequest() {
        RequestIdentifier<T> i = getRequestIdentifier();
        if (null == i)
            return null;
        i.retire();
        return i.getRequest();
    }

    public Iterable<RequestIdentifier<T>> iter() {
        return (Iterable) requests;
    }

    /**
     * Get the current request.
     *
     * @return the current request.
     */
    public T getRequest() {
        RequestIdentifier<T> i = getRequestIdentifier();
        if (null == i)
            return null;
        return i.getRequest();
    }

    /**
     * A request identifier in a sequential request container.
     */
    private class Identifier extends SimpleRequestIdentifier<T> {
        public Identifier(T request) {
            super(request);
        }

        @Override
        public void retire() {
            super.retire();
            if (requestsActive == 0 || requests.isEmpty())
                throw new AssertionError();
            boolean found = requests.remove(this);
            if (!found)
                throw new AssertionError("request not in queue");
            requestsActive--;
            Identifier next = requests.peekFirst();
            if (null == next || next.queued)
                return;
            if (requestsActive == 0 || overlap)
                next.send(mq);
        }
    }

    /**
     * Add a request to the queue
     *
     * @param request the request to add
     * @return a handle that represents the queued request
     */
    public RequestIdentifier<T> addRequest(final T request) {
        final Identifier identifier = new Identifier(request);
        requests.addLast(identifier);
        // only send immediately if we are allowed to
        if (overlap || requestsActive == 0) {
            identifier.send(mq);
            requestsActive += 1;
        }
        return identifier;
    }

    /**
     * Re-send all active requests.
     */
    @Override
    public void restart() {
        LinkedList<Identifier> requestsOld = requests;
        requests = new LinkedList<Identifier>();
        for (Identifier r : requestsOld) {
            addRequest(r.getRequest());
        }
    }
}
