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

jingrow.ui.form.on('Wireguard Peer', {
	refresh: function (frm) {
		frm.add_fetch('server_name', 'ip', 'ip');
		frm.add_fetch('server_name', 'private_ip', 'private_ip');
		frm.add_fetch('server_name', 'title', 'peer_name');

		[
			[__('Setup Wireguard'), 'setup_wireguard', false],
			[__('Ping Peer'), 'ping_peer', false],
			[__('Fetch Private Network'), 'fetch_peer_private_network', false],
			[__('Generate Config'), 'generate_config', false],
			[__('Generate QR'), 'generate_qr_code', false],
		].forEach(([label, method, confirm, condition]) => {
			if (typeof condition === 'undefined' || condition) {
				frm.add_custom_button(
					label,
					() => {
						if (confirm) {
							jingrow.confirm(
								`Are you sure you want to ${label.toLowerCase()}?`,
								() =>
									frm.call(method).then((r) => {
										if (r.message) {
											jingrow.msgprint(r.message);
										} else {
											frm.refresh();
										}
									}),
							);
						} else {
							frm.call(method).then((r) => {
								if (r.message) {
									jingrow.msgprint(r.message);
								} else {
									frm.refresh();
								}
							});
						}
					},
					__('Actions'),
				);
			}
		});
	},
});
