/*
 * PEnetration TEsting Proxy (PETEP)
 *
 * Copyright (C) 2020 Michal Válka
 *
 * This program 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 of the
 * License, or (at your option) any later version.
 *
 * This program 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 this program. If
 * not, see <https://www.gnu.org/licenses/>.
 */
package com.warxim.petep.core.pdu;

import com.warxim.petep.extension.PetepAPI;

import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Queue of PDUs.
 * <p>Based on {@link BlockingQueue}.</p>
 */
@PetepAPI
public class PduQueue {
    private final BlockingQueue<PDU> queue;

    /**
     * Constructs PDU queue.
     */
    public PduQueue() {
        queue = new LinkedBlockingQueue<>();
    }

    /**
     * Add PDU to queue.
     * @param pdu PDU to be added to the queue
     */
    public void add(PDU pdu) {
        queue.add(pdu);
    }

    /**
     * Obtains PDU from queue (blocks until there is PDU).
     * @return PDU from queue
     * @throws InterruptedException If interrupted while waiting
     */
    public PDU take() throws InterruptedException {
        return queue.take();
    }

    /**
     * Obtains and removes the head of the queue.
     * @return PDU from queue or empty optional if the queue is empty
     */
    public Optional<PDU> poll() {
        return Optional.ofNullable(queue.poll());
    }

    /**
     * Get queue size.
     * @return Size of the queue
     */
    public int size() {
        return queue.size();
    }

    /**
     * Clears queue.
     */
    public void clear() {
        queue.clear();
    }

    /**
     * Checks if the queue is empty.
     * @return {@code true} if the queue is empty
     */
    public boolean isEmpty() {
        return queue.isEmpty();
    }
}
