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

module.exports = new Class({
	Extends: Vn.Component,
	Properties: {
		conn: {
			type: Db.Connection
			,set(x) {
				this.link({_conn: x}, {'loading-changed': this._onConnLoadChange});
			}
			,get() {
				return this._conn;
			}
		}
	}

	,initialize(props) {
		Vn.Component.prototype.initialize.call(this, props);
		this.loadTemplateFromString(Tpl);
	
		//this.$.socialBar.conn = this._conn;
		
		var self = this;
		this.$.form.onsubmit = function() {
			self._onSubmit();
			return false;
		};
	}
	
	,_onConnLoadChange(conn, isLoading) {
		if (isLoading)
			this.$.spinner.start();
		else
			this.$.spinner.stop();
	}

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

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

		if (lastUser)
			this.$.user.value = lastUser;
	
		this._focusUserInput();
	}
	
	,async _onSubmit() {
		this._disableUi(true);
		try {
			await this._conn.open(
				this.$.user.value,
				this.$.pass.value,
				this.$.remember.checked
			);

			const user = this.$.user.value;
			if (user) localStorage.setItem('hederaLastUser', user);
			this.emit('login');
		} catch (err) {
			this._focusUserInput();
			if (err.statusCode == 401)
				Htk.Toast.showError(_('Invalid login'));
			else
				throw err;
		} finally {
			this.$.pass.value = '';
			this._disableUi(false);
		}
	}
	
	,hide() {
		Vn.Node.remove(this.node);
	}
	
	,_focusUserInput() {
		var userEntry = this.$.user;
		userEntry.focus();
		userEntry.select();
	}
	
	,_disableUi(disabled) {
		this.$.user.disabled = disabled;
		this.$.pass.disabled = disabled;
		this.$.submit.disabled = disabled;
	}
	
	,async onPasswordLost() {
		var recoverUser = this.$.user.value;
	
		if (!recoverUser) {
			Htk.Toast.showError(_('Please write your user name'));
			return;
		}
		
		await this._conn.send('user/recover-password', {recoverUser});
		Htk.Toast.showMessage(_('A mail has been sent wich you can recover your password'));
	}
});

