frappe.ui.form.on('Kapital Bank Login', {
	refresh(frm) {
		frm.add_custom_button(__('Login'), () => {
			do_login(frm);
		}, __('Actions'));

		frm.add_custom_button(__('Logout'), () => {
			do_logout(frm);
		}, __('Actions'));
	}
});

function do_login(frm) {
	if (frm.is_new() || frm.is_dirty()) {
		frm.save('Save', () => { _call_login(frm); });
	} else {
		_call_login(frm);
	}
}

function _call_login(frm) {
	frappe.show_progress(__('Logging in...'), 0, 100, __('Connecting to Kapital Bank...'));

	frappe.call({
		method: 'kapital_bank.auth.login',
		args: { login_name: frm.doc.name },
		freeze: false,
		callback(r) {
			frappe.hide_progress();
			if (r.exc) {
				frappe.msgprint({ title: __('Error'), message: r.exc, indicator: 'red' });
				return;
			}
			const res = r.message;
			if (res && res.success) {
				frappe.show_alert({ message: __('Login successful'), indicator: 'green' }, 5);
				frm.reload_doc();
			} else {
				frappe.msgprint({
					title: __('Login Failed'),
					message: res ? res.message : __('Unknown error'),
					indicator: 'red'
				});
			}
		},
		error() {
			frappe.hide_progress();
			frappe.msgprint({ title: __('Error'), message: __('Request failed'), indicator: 'red' });
		}
	});
}

function do_logout(frm) {
	frappe.confirm(__('Are you sure you want to logout?'), () => {
		frappe.call({
			method: 'kapital_bank.auth.logout',
			args: { login_name: frm.doc.name },
			freeze: true,
			callback(r) {
				if (r.message && r.message.success) {
					frappe.show_alert({ message: __('Logged out successfully'), indicator: 'green' }, 5);
					frm.reload_doc();
				}
			}
		});
	});
}
