import './style.scss';

export default new Class({
	Extends: Hedera.Form,
	Template: require('./ui.xml'),
	
	activate() {
		this.$.userModel.setInfo('c', 'myClient', 'hedera');
		this.$.userModel.setInfo('u', 'myUser', 'account');

		if (this.hash.$.verificationToken)
			this.onPassChangeClick();
	}

	,onPassChangeClick() {
		this.$.oldPassword.value = '';
		this.$.newPassword.value = '';
		this.$.repeatPassword.value = '';

		var verificationToken = this.hash.$.verificationToken;
		this.$.oldPassword.style.display = verificationToken ? 'none' : 'block';
		this.$.changePassword.show();

		if (verificationToken)
			this.$.newPassword.focus();
		else
			this.$.oldPassword.focus();
	}

	,async onPassModifyClick() {
		const form = this.$.changePassword.node;
		Vn.Node.disableInputs(form);
		try {
			const oldPassword = this.$.oldPassword.value;
			const newPassword = this.$.newPassword.value;
			const repeatedPassword = this.$.repeatPassword.value;
	
			try {
				if (newPassword == '' && repeatedPassword == '')
					throw new Error(_('Passwords empty'));
				if (newPassword !== repeatedPassword)
					throw new Error(_('Passwords doesn\'t match'));
			} catch (err) {
				return Htk.Toast.showError(err.message);
			}
		
			const verificationToken = this.hash.$.verificationToken;
			const params = {newPassword};

			try {
				if (verificationToken) {
					params.verificationToken = verificationToken;
					await this.conn.send('user/restore-password', params);
				} else {
					let userId = this.gui.user.id;
					params.oldPassword = oldPassword;
					await this.conn.patch(
						`Accounts/${userId}/changePassword`, params);
				}
			} catch(err) {
				Htk.Toast.showError(err.message);

				if (verificationToken)
					this.$.newPassword.select();
				else
					this.$.oldPassword.select();

				return;
			}

			this.hash.unset('verificationToken');
			await this.conn.open(this.gui.user.name, newPassword);
			this.$.changePassword.hide();
		} finally {
			Vn.Node.disableInputs(form, false);
		}
		
		Htk.Toast.showMessage(_('Password changed!'));
	}
	
	,onPassInfoClick() {
		this.$.passwordInfo.show();
	}
});

