var BaseDialog = require('libresignage/ui/components/Dialog/BaseDialog');

/**
* A class representing a select dialog.
*
* @memberof module:libresignage/ui/components/Dialog
*/
class SelectDialog extends BaseDialog {
	/**
	* Construct a new SelectDialog object.
	*
	* @param {string}              title    The title of the dialog.
	* @param {string}              body     The body of the dialog.
	* @param {object}              options  An object of options.
	* @param {BaseDialog_callback} callback A callback function.
	*/
	constructor(title, body, options, callback) {
		super(title, body);
		this.value = null;

		// Addd the select dialog options, buttons and event listeners.
		this.dialog.querySelector('.dialog').innerHTML += `
			<div class="dialog-interaction">
				<select class="form-control mb-2 dialog-select"></select>
			</div>
			<div class="dialog-interaction">
				<button class="btn btn-primary btn-dialog btn-dialog-ok">
					Ok
				</button>
				<button class="btn btn-primary btn-dialog btn-dialog-cancel">
					Cancel
				</button>
			</div>
		`;

		for (let key in options) {
			this.dialog.querySelector('.dialog-select').innerHTML += `
				<option value=${key}>${options[key]}</option>
			`;
		}
		this.value = options[
			this.dialog.querySelector('.dialog-select').value
		];

		this.dialog
			.querySelector('.btn-dialog-ok')
			.addEventListener('click', () => {
				super.hide();
				callback(true);
			});
		this.dialog
			.querySelector('.btn-dialog-cancel')
			.addEventListener('click', () => {
				super.hide();
				callback(false);
			});
		this.dialog
			.querySelector('.dialog-select')
			.addEventListener('change', e => {
				this.value = e.target.value;
			});

		super.show();
	}

	/**
	* Set focus on the OK button.
	*/
	focus_default() {
		document.querySelector('.btn-dialog-ok').focus();
	}
	
	/**
	* Get the value of the dialog select box. This is one of the keys
	* supplied in the 'options' parameter of the constructor.
	*
	* @returns {mixed} The selected option.
	*/
	get_value() { return this.value; }
}
module.exports = SelectDialog;
