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

/**
* A class representing a prompt dialog.
*
* @memberof module:libresignage/ui/components/Dialog
*/
class PromptDialog extends BaseDialog {
	/**
	* Construct a new PromptDialog object.
	*
	* @param {string}              title      The title of the dialog.
	* @param {string}              body       The body of the dialog.
	* @param {array}               validators A list of validators to use
	*                                         for the prompt.
	* @param {BaseDialog_callback} callback   The callback function.
	*/
	constructor(title, body, validators, callback) {
		super(title, body);
		this.values = null;

		// Add the prompt dialog inputs, buttons and event listeners.
		this.dialog.querySelector('.dialog').innerHTML += `
			<div class="dialog-interaction">
				<div class="dialog-input-grp">
					<input class="dialog-input form-control"></input>
					<div class="invalid-feedback my-0"></div>
				</div>
			</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>
		`;
		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-input")
			.addEventListener('change', e => {
				this.value = e.target.value;
			})

		// Setup caller-supplied validators.
		this.validator_trigger = new ValidatorTrigger(
			[new ValidatorSelector(
				this.dialog.querySelector(".dialog-input"),
				this.dialog.querySelector(".dialog-input-grp"),
				validators
			)],
			valid => {
				this.dialog
					.querySelector(".btn-dialog-ok")
					.disabled = !valid;
			}
		)

		super.show();
	}

	/**
	* Set focus on the OK button.
	*/
	focus_default() {
		document.querySelector('.btn-dialog-ok').focus();
	}

	/**
	* Get the value of the prompt input.
	*
	* @returns {string} The prompt input value.
	*/
	get_value() { return this.value; }
}
module.exports = PromptDialog;
