const Queue = require('./queue');

// Inspired by:
// https://stackoverflow.com/questions/53540348/js-async-await-tasks-queue#53540586

class ActionsQueue extends Queue {

	constructor (items = []) {
		super(items);

		this.pending = false;
	}

	enqueue (action) {
		return new Promise ((resolve, reject) => {
			super.enqueue({ action, resolve, reject });
			this.dequeue();
		});
	}

	async dequeue () {

		if (this.pending) {
			return false;
		}

		const item = super.dequeue();

		if (!item) {
			return false;
		}

		try {

			this.pending = true;

			const result = await item.action(this);

			this.pending = false;
			item.resolve(result);
		} catch (err) {
			this.pending = false;
			item.reject(err);
		} finally {
			this.dequeue();
		}

	}

}

module.exports = ActionsQueue;
