/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Queue } from "./queue.mjs";
import { internalSymbol } from "../constants.mjs";
import { validateObject } from "./validate.mjs";

export { UniqueQueue };

/**
 * An UniqueQueue is a queue that contains items only once.
 *
 * @license AGPLv3
 * @since 1.4.0
 * @copyright Volker Schukai
 * @summary A queue for unique values
 */
class UniqueQueue extends Queue {
	/**
	 *
	 */
	constructor() {
		super();
		this[internalSymbol] = {
			unique: new WeakSet(),
		};
	}

	/**
	 * Add a new element to the end of the queue.
	 *
	 * @param {object} value
	 * @return {Queue}
	 * @throws {TypeError} value is not a object
	 */
	add(value) {
		validateObject(value);

		if (!this[internalSymbol].unique.has(value)) {
			this[internalSymbol].unique.add(value);
			super.add(value);
		}

		return this;
	}

	/**
	 * remove all entries
	 *
	 * @return {Queue}
	 */
	clear() {
		super.clear();
		this[internalSymbol].unique = new WeakSet();
		return this;
	}

	/**
	 * Remove the element at the front of the queue
	 * If the queue is empty, return undefined.
	 *
	 * @return {object}
	 */
	poll() {
		if (this.isEmpty()) {
			return undefined;
		}
		const value = this.data.shift();
		this[internalSymbol].unique.delete(value);
		return value;
	}
}
