/**
 * @file    param.js
 * @brief   定值管理页面 — 多定值区展开
 */


Router.register('#param', function(c) {
	var signals = SignalStore.get('param');
	var rows = '';

	if (signals.length === 0)
	{
		rows = '<tr class="empty-row"><td colspan="5">' + I18n.t('signal.no_data') + '</td></tr>';
	}
	else
	{
		signals.forEach(function(s) {
			var zones = s.setting_zone_list || [];
			var zoneHtml = '';
			zones.forEach(function(z) {
				zoneHtml += '<div style="display:flex;gap:8px;align-items:center;padding:2px 0;">'
					+ '<span style="color:var(--text-muted);font-family:var(--font-mono);width:40px;">#' + esc(z.id) + '</span>'
					+ '<span style="font-family:var(--font-mono);color:var(--accent);">' + esc(z.val) + '</span>'
					+ '<button class="btn btn-sm" onclick="ParamActions.set(\'' + esc(s.saddr) + '\',\'' + esc(z.id) + '\')">' + I18n.t('signal.set') + '</button>'
					+ '</div>';
			});
			rows += '<tr>'
				+ '<td class="cell-mono">' + esc(s.saddr) + '</td>'
				+ '<td class="cell-desc">' + esc(s.desc || '') + '</td>'
				+ '<td class="cell-mono">' + esc(s.type || '?') + '</td>'
				+ '<td>' + (zoneHtml || '\u2014') + '</td>'
				+ '<td><button class="btn btn-danger btn-sm" onclick="SignalActions.del(\'param\',\'' + esc(s.saddr) + '\')">' + Icon.get('trash') + '</button></td>'
				+ '</tr>';
		});
	}

	c.innerHTML = '<div class="card">'
		+ '<div class="card-header"><span>PARAM \u2014 ' + signals.length + ' signals</span>'
		+ '<button class="btn btn-primary btn-sm" onclick="SignalActions.add(\'param\')">' + Icon.get('plus') + ' ' + I18n.t('signal.add') + '</button>'
		+ '</div>'
		+ '<div class="table-wrap"><table class="signal-table">'
		+ '<thead><tr><th>' + I18n.t('signal.saddr') + '</th><th>' + I18n.t('signal.desc') + '</th><th>' + I18n.t('signal.type') + '</th><th>' + I18n.t('signal.zone') + '</th><th>' + I18n.t('signal.action') + '</th></tr></thead>'
		+ '<tbody>' + rows + '</tbody>'
		+ '</table></div></div>';
});

var ParamActions = {
	set: function(saddr, zoneId) {
		showModal(I18n.t('signal.set_title') + ' \u2014 ' + esc(saddr) + ' ' + I18n.t('signal.zone') + ' ' + zoneId,
			'<div class="form-group"><label class="form-label">' + I18n.t('signal.new_val') + '</label><input class="form-input" id="mf-val" placeholder="Value"></div>',
			function(ov) {
				var val = getModalVal(ov, '#mf-val');
				WsClient.send({ saddr: saddr, signal_type: 'param', curd: 'set', signal_data: val, setting_zone: zoneId });
				toast(I18n.t('toast.set_sent') + ': ' + saddr + '#' + zoneId + ' = ' + val, 'success');
				ov.remove();
			}, I18n.t('signal.set'));
	}
};
