var Popup = require('./popup');

/**
 * Class to show message dialogs with buttons.
 */
var Dialog = new Class();
module.exports = Dialog;

var Button =
{
	 OK     : 1 << 1
	,ACCEPT : 1 << 2
	,CANCEL : 1 << 3
	,RETRY  : 1 << 4
	,YES    : 1 << 5
	,NO     : 1 << 6
};

var labels =
[{
	response: Button.NO
	,label: 'No'
},{
	response: Button.CANCEL
	,label: 'Cancel'
},{
	response: Button.RETRY
	,label: 'Retry'
},{
	response: Button.ACCEPT
	,label: 'Accept'
},{
	response: Button.OK
	,label: 'Ok'
},{
	response: Button.YES
	,label: 'Yes'
}];

Button.CANCEL_ACCEPT = Button.CANCEL | Button.ACCEPT;
Button.RETRY_CANCEL = Button.RETRY | Button.CANCEL;
Button.YES_NO = Button.YES | Button.NO;

Dialog.extend({
	 Button: Button
});

Dialog.implement({
	Extends: Popup
	,Tag: 'htk-dialog'
	,Properties:
	{
		/**
		 * The message displayed to the user.
		 */
		message:
		{ 
			type: String
			,set: function(x) {
				this._message = x;
			}
			,get: function() {
				return this._message;
			}
		}
		/**
		 * The dialog icon.
		 */
		,icon:
		{ 
			type: String
			,set: function(x) {
				this._icon = x;
			}
			,get: function() {
				return this._icon;
			}
		}
		/**
		 * The dialog buttons.
		 */
		,buttons:
		{
			enumType: Button
			,set: function(x) {
				this._buttons = x;
			}
			,get: function() {
				return this._buttons;
			}
		}
	}
	
	,_modal: true
	,_icon: 'info'
	,_buttons: Button.ACCEPT
	
	,open: function() {
		this.parent();
	
		// Dialog body

		var root = this.createElement('div');
		root.className = 'htk-dialog';
		
		var body = this.createElement('div');
		root.appendChild(body);
		
		if (this._icon) {
			var icon = new Htk.Icon({
				doc: this.doc,
				icon: this._icon
			});
			body.appendChild(icon.node);
		}
		
		var p = this.createElement('p');
		body.appendChild(p);
		
		if (this._message)
			p.appendChild(this.createTextNode(this._message));
		
		var clear = this.createElement('div');
		clear.style.clear = 'both';
		body.appendChild(clear);

		// Button bar
		
		var buttonBar = this._buttonBar = this.createElement('div');
		buttonBar.className = 'button-bar';
		root.appendChild(buttonBar);
		
		var i = labels.length;

		while (i--)
		if (this._buttons & labels[i].response)
			this.createButton(_(labels[i].label), labels[i].response);
		
		var clear = this.createElement('div');
		clear.style.clear = 'both';
		root.appendChild(clear);

		this.childNode = root;
	}

	,hide(response) {
		if (!this._isOpen) return;
		this.parent();
		this.signalEmit('response', response);
	}
	
	,createButton: function(label, response) {
		var button = this.createElement('button');
		button.className = 'thin';
		button.appendChild(this.createTextNode(label));
		button.addEventListener('click',
			this.hide.bind(this, response));
		this._buttonBar.appendChild(button);
	}
});