var Assert = require('assert');

/**
* A UI component that allows the user to confirm/cancel an operation.
*
* @memberof module:libresignage/ui/components.
*/
class DropConfirm {
	/**
	* Construct a new DropConfirm object.
	*
	* The container provided to this function *must* have an ID.
	*
	* @param {HTMLElement} container The container where the DropConfirm
	*                                is created.
	*/
	constructor(container) {
		Assert.ok(container.id !== '', 'Container must have an ID.');

		this.container = container;
		this.container.classList.add('dropdown', 'dropconfirm');
		this.container.innerHTML = DropConfirm.make_html(container.id);

		// Attach open/close event listeners.
		this.container.addEventListener('show.bs.dropdown', e => {
			this.container.dispatchEvent(
				new Event('component.dropconfirm.show')
			);
		});
		this.container.addEventListener('hide.bs.dropdown', e => {
			this.container.dispatchEvent(
				new Event('component.dropconfirm.hide')
			);
		});

		// Attach button event listeners.
		this.container
			.querySelector('.dropconfirm-confirm')
			.addEventListener('click', () => {
				this.container.dispatchEvent(
					new Event('component.dropconfirm.confirm')
				);
			});
		this.container
			.querySelector('.dropconfirm-cancel')
			.addEventListener('click', () => {
				this.container.dispatchEvent(
					new Event('component.dropconfirm.cancel')
				);
			});
	}

	/**
	* Create the DropConfirm HTML from a template.
	*
	* @param {string} container_id The ID of the container where the DropConfirm
	*                              is created.
	*
	* @returns {string} The generated HTML.
	*/
	static make_html(container_id) {
		return `
			<button id="btn-${container_id}-dropconfirm"
				type="button"
				class="btn dropdown-toggle dropconfirm-open"
				data-toggle="dropdown"
				aria-haspopup="true"
				aria-expanded="false">
			</button>
			<div class="dropdown-menu dropconfirm-menu"
				aria-labelledby="btn-${container_id}-dropconfirm">
				<div class="dropconfirm-content"></div>
				<button type="button" class="btn btn-primary dropconfirm-confirm">
					<i class="fas fa-check"></i>
				</button>
				<button type="button" class="btn btn-danger dropconfirm-cancel">
					<i class="fas fa-times"></i>
				</button>
			</div>
		`;
	}

	/**
	* Set the HTML of the open button.
	*
	* @param {string} The HTML to set.
	*/
	set_button_html(html) {
		this.container.querySelector('.dropconfirm-open').innerHTML = html;
	}

	/**
	* Set the HTML content.
	*
	* @param {string} The HTML to set.
	*/
	set_content_html(html) {
		this.container.querySelector('.dropconfirm-content').innerHTML = html;
	}
}
module.exports = DropConfirm;
