
var Tpl = require ('./login.xml');

require ('./login.css');

/**
 * The login component.
 */
module.exports = new Class
({
	Extends: Vn.Component,
	Properties:
	{
		/**
		 * The main connection object.
		 */
		conn:
		{
			type: Db.Connection
			,set: function (x)
			{
				this.link ({_conn: x}, {'loading-changed': this._onConnLoadChange});
			}
			,get: function ()
			{
				return this._conn;
			}
		}
	}

	,initialize: function (props)
	{
		this.parent (props);
		this.loadTemplateFromString (Tpl);
	
		this.$.socialBar.conn = this._conn;
		
		var self = this;
		this.$.form.onsubmit = function ()
		{
			self._onSubmit ();
			return false;
		};
	}

	,show: function ()
	{
		document.body.appendChild (this.node);

		var lastUser = localStorage.getItem ('hederaLastUser');

		if (lastUser)
			this.$.user.value = lastUser;
	
		this._focusUserInput ();
	}
	
	,hide: function ()
	{
		Vn.Node.remove (this.node);
	}
	
	,_onConnLoadChange: function (conn, isLoading)
	{
		if (isLoading)
			this.$.spinner.start ();
		else
			this.$.spinner.stop ();
	}
	
	,_onSubmit: function ()
	{
		this._conn.open (
			this.$.user.value,
			this.$.pass.value,
			this.$.remember.checked,
			this._onConnOpen.bind (this)
		);
		this._disableUi (true);
	}
	
	,_onConnOpen: function (conn, success, error)
	{
		this.$.pass.value = '';
		this._disableUi (false);

		if (success)
		{
			var user = this.$.user.value;
		
			if (user)
				localStorage.setItem ('hederaLastUser', user);

			this.emit ('login');
		}
		else
		{
			this._focusUserInput ();
			throw error;
		}
	}
	
	,_focusUserInput: function ()
	{
		var userEntry = this.$.user;
		userEntry.focus ();
		userEntry.select ();
	}
	
	,_disableUi: function (disabled)
	{
		this.$.user.disabled = disabled;
		this.$.pass.disabled = disabled;
		this.$.submit.disabled = disabled;
	}
	
	,onPasswordLost: function ()
	{
		var user = this.$.user.value;
	
		if (!user)
			Htk.Toast.showError (_('Please write your user name'));
		else
			this._conn.send ('core/recover-password', {recoverUser: user},
				this._onPasswordRecovered.bind (this));
	}
	
	,_onPasswordRecovered: function (json, error)
	{
		if (error)
			throw error;

		Htk.Toast.showMessage (_('A mail has been sent wich you can recover your password'));
	}
});

