/**
* Callback function for dialog constructors..
*
* @callback BaseDialog_callback
* @alias    BaseDialog_callback
*
* @param {boolean} state True if the user clicked OK, false otherwise.
*/

/**
* A base dialog class for creating HTML dialogs.
*
* @memberof module:libresignage/ui/components/Dialog
*/
class BaseDialog {
	constructor(title, body) {
		this.prevent_tab_listener = e => {
			if (e.keyCode === 9) {
				e.preventDefault();
			}
		}

		this.create(title, body);
	}

	/**
	* Create a base dialog HTMLElement.
	*
	* @param {string} title The title of the dialog.
	* @param {string} body  The body of the dialog.
	*/
	create(title, body) {
		this.dialog = document.createElement('div');
		this.dialog.classList.add('dialog-overlay', 'dialog-overlay-hidden');
		this.dialog.innerHTML = `
			<div class="dialog container">
				<h3 class="dialog-title display-5">${title}</h3>
				<div class="dialog-body">${body}</div>
			</div>
		`;
		document.body.appendChild(this.dialog);
	}

	/**
	* Show a dialog.
	*
	* This function also sets up an event listener that prevents
	* the user from using tab to navigate on the page.
	*/
	show() {
		this.dialog.classList.remove('dialog-overlay-hidden');
		document.addEventListener('keydown', this.prevent_tab_listener);
		this.focus_default();
	}

	/**
	* Hide a dialog.
	*
	* This function also removes the tab-prevention event listener
	* created by BaseDialog.show().
	*
	* @param {boolean} destroy If true, the HTML DOM elements are also
	*                          removed. Set this to false if you intend
	*                          to call .show()/.hide() multiple times.
	*/
	hide(destroy=true) {
		document.removeEventListener('keydown', this.prevent_tab_listener);
		this.dialog.classList.add('dialog-overlay-hidden');
		document.body.removeChild(this.dialog);
	}

	/**
	* Set focus on the default option in a dialog.
	*
	* Override this function in classes extending BaseDialog.
	*/
	focus_default() {}
}
module.exports = BaseDialog;
