var Component = require('vn/component');
var Toast = require('../toast');
var Tpl = require('./ui.xml').default;

/**
 * A change password popup.
 */
module.exports = new Class({
	Extends: Component,
	Tag: 'htk-change-password',
	Properties: {
		/**
		 * The token url.
		 */
		token: {
			type: String
			,set(value) {
				this._token = value;
			}
			,get() {
				return this._token;
			}
		},
		conn: {
			type: Db.Connection
			,set(x) {
				this._conn = x
			}
			,get() {
				return this._conn;
			}
		},
		user: {
			type: Object
		}
	},

	initialize(props) {
		Component.prototype.initialize.call(this, props);
	},

	async open() {
		this.passwordForm = await this.conn.get('UserPasswords/findOne')
		this.loadTemplateFromString(Tpl);

		this.$.oldPassword.value = '';
		this.$.newPassword.value = '';
		this.$.repeatPassword.value = '';

		this.$.oldPassword.style.display = this.token ? 'none' : 'block';
		this.$.changePassword.open();

		if (this.token)
			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 Toast.showError(err.message);
			}
		
			const params = {newPassword};


			try {
				if (this.token) {
					const headers = {
						Authorization: this.token
					};
					await this.conn.post('VnUsers/reset-password', params, {headers});
				} else {
					params.userId = this.user.id;
					params.oldPassword = oldPassword;
					
					await this.conn.patch(`Accounts/change-password`, params);
				}
			} catch(err) {
				Toast.showError(err.message);

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

				return;
			}

			if(this.user)
				await this.conn.open(this.user.name, newPassword);
			this.$.changePassword.hide();
		} finally {
			Vn.Node.disableInputs(form, false);
		}
		
		Toast.showMessage(_('Password changed!'));
	}
});