import { sidebarTemplate, rebootDeviceBtnHandler } from "./devices-funcs.js";
import { deviceDetailsPopup } from "./device-details-popup.js";
import deviceStateComponent from "./device-state-component.js";

function prepareData(data) {
	const preparedData = [];
	for(let device of data.devices) {
		device = Helper.unification.deviceFieldsUnification(device);

		preparedData.push({
			deviceName: device.name,
			alias: device.alias,
			connectionStatus: Helper.template.connectionStatusBadge(device.connection_status),
			state: `<div
				class="device-state-container"
				data-device-id="${device.id}"
				data-device-type="${device.type}"
				data-connection-status="${device.connection_status}"
			></div>`,
			ip: `<code class="code">${device.ip}</code>`,
			actions: `
				<div class="f-grid g-2">
					<button 
						class="btn btn-secondary btn-small details-btn" 
						data-device='${JSON.stringify(device)}'
						type="button"
					>Details</button>

					<button 
						class="btn btn-warning btn-small reboot-btn" 
						data-device-id="${device.id}" 
						data-device-name="${device.name}" 
						data-device-alias="${device.alias}" 
						type="button"
					>Reboot</button>
				</div>
			`
		});
	}

	return preparedData;
}

function renderingMainTable(scr, data, total) {
	scr.currentScreen.DOMObject.querySelector(".main-container").innerHTML = Helper.template.table(
		"Devices list", 
		{
			deviceName: "Device name", 
			connectionStatus: "Connect",
			state: "State",
			ip: "IP", 
			actions: "Actions"
		},
		data,
		`<span class="table-meta">Total: <span class="total">${total}</span> devices</span>`
	);
}

function initMainTableInteractiveElements(scr, sh_api) {
	scr.currentScreen.DOMObject.querySelectorAll(".reboot-btn").forEach(btn => {
		btn.addEventListener("click", e => {
			if(e.currentTarget.getAttribute("disabled")) {
				return ;
			}

			rebootDeviceBtnHandler(sh_api, e.currentTarget);
		});
	});

	scr.currentScreen.DOMObject.querySelectorAll(".details-btn").forEach(btn => {
		btn.addEventListener("click", e => {
			const device = {
				state: "",
				...JSON.parse(e.currentTarget.dataset.device)
			}
			deviceDetailsPopup(device, sh_api).show();
		});
	});
}

function loadDeviceStates(scr, sh_api, concurrency = 4) {
	const containers = Array.from(scr.currentScreen.DOMObject.querySelectorAll(".device-state-container"));
	let cursor = 0;
	let active = 0;

	const runNext = () => {
		while(active < concurrency && cursor < containers.length) {
			const container = containers[cursor++];

			if(container.dataset.connectionStatus === "lost") {
				container.innerHTML = `<span class="badge badge-error"><i class="ph ph-wifi-slash normalize"></i> Offline</span>`;
				continue;
			}

			active++;
			const component = deviceStateComponent(
				sh_api,
				container.dataset.deviceId,
				container.dataset.deviceType,
				() => {
					active--;
					runNext();
				}
			);
			container.append(component);
		}
	};

	runNext();
}

function list(sh_api) {
	return {
		alias: "devices",
		renderer: () => {
			return Helper.template.mainTemplate(sidebarTemplate("devices"));
		},

		initer: scr => {
			try {
				sh_api.devices.list((err, resp, meta) => {

					if(err || !resp || meta.status_code != 200) {
						throw "Err";
					}

					renderingMainTable(scr, prepareData(resp.data), resp.data.total);
					initMainTableInteractiveElements(scr, sh_api);
					loadDeviceStates(scr, sh_api);

					scr.ready();
				});
			} catch(e) {
					console.error("sh_api.devices.list", e);
					return scr.error("Server API ERROR", "");
			}
		}
	};
}

export {
	list
}
