// Copyright (c) 2019, JINGROW
// For license information, please see license.txt

jingrow.ui.form.on('Bench', {
	onload: function (frm) {
		frm.set_query('candidate', function () {
			return {
				filters: {
					group: frm.pg.group,
				},
			};
		});
	},

	refresh: function (frm) {
		frm.add_web_link(
			`/dashboard/groups/${frm.pg.group}/versions/${frm.pg.name}`,
			__('Visit Dashboard'),
		);

		[
			[__('Archive'), 'archive'],
			[__('Sync Sites Info'), 'sync_info'],
			[__('Sync Sites Analytics'), 'sync_analytics'],
			[__('Update All Sites'), 'update_all_sites'],
			[
				__('Generate NGINX Config'),
				'generate_nginx_config',
				frm.pg.status === 'Active',
			],
			[
				__('Remove SSH User from Proxy'),
				'remove_ssh_user',
				frm.pg.is_ssh_proxy_setup,
			],
			[
				__('Add SSH User to Proxy'),
				'add_ssh_user',
				!frm.pg.is_ssh_proxy_setup,
			],
			[__('Restart'), 'restart', frm.pg.status === 'Active'],
			[__('Rebuild'), 'rebuild', frm.pg.status === 'Active'],
			[__('Retry New Bench'), 'retry_bench', frm.pg.status === 'Broken'],
			[__('Force Update Limits'), 'force_update_limits'],
		].forEach(([label, method, condition]) => {
			if (typeof condition === 'undefined' || condition) {
				frm.add_custom_button(
					label,
					() => {
						jingrow.confirm(
							`Are you sure you want to ${label.toLowerCase()} this bench?`,
							() => frm.call(method).then((r) => frm.refresh()),
						);
					},
					__('Actions'),
				);
			}
		});

		frm.add_custom_button(
			'Move sites',
			() => {
				let d = new jingrow.ui.Dialog({
					title: 'Move sites',
					fields: [
						{
							fieldtype: 'Link',
							fieldname: 'server',
							label: 'Server',
							options: 'Server',
							reqd: 1,
						},
					],
					primary_action({ server }) {
						frm.call('move_sites', { server }).then((r) => {
							if (!r.exc) {
								jingrow.show_alert(
									`Scheduled migrations for sites to ${server}`,
								);
							}
							d.hide();
						});
					},
				});
				d.show();
			},
			__('Actions'),
		);
	},
});
