'use strict';
'require rpc';

const callLogRead = rpc.declare({
	object: 'log',
	method: 'read',
	params: ['lines', 'stream', 'oneshot'],
	expect: {}
});

function Logview(logtag, name) {
	return L.view.extend({
		load: () => Promise.resolve(),

		render: function () {
			const pollFn = () => {
				return callLogRead(1000, false, true).then(res => {
					const logEl = document.getElementById('logfile');
					if (!logEl) return;
					const filtered = (res?.log ?? [])
						.filter(entry => !logtag || entry.msg.includes(logtag))
						.map(entry => {
							const d = new Date(entry.time);
							const pad = n => String(n).padStart(2, '0');
							const date = `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()}`;
							const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
							return `[${date}-${time}] ${entry.msg}`;
						});
					logEl.value = filtered.length > 0
						? filtered.join('\n')
						: _('No %s related logs yet!').format(name);
					logEl.scrollTop = logEl.scrollHeight;
				});
			};

			this._pollFn = pollFn;
			L.Poll.add(pollFn);

			return E('div', { class: 'cbi-map' }, [
				E('div', { class: 'cbi-section' }, [
					E('div', { class: 'cbi-section-descr' },
						_('The syslog output, pre-filtered for messages related to: %s').format(name)),
					E('textarea', {
						id: 'logfile',
						style: 'min-height: 500px; max-height: 90vh; width: 100%; padding: 5px; font-family: monospace; resize: vertical;',
						readonly: 'readonly',
						wrap: 'off'
					})
				])
			]);
		},

		unload: function () {
			if (this._pollFn) {
				L.Poll.remove(this._pollFn);
				this._pollFn = null;
			}
		},

		handleSaveApply: null,
		handleSave: null,
		handleReset: null
	});
}

return L.Class.extend({ Logview });
