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

export function areaDevicesModal(area, sh_api) {
	console.log("areaDevicesModal", area);

	return Modals.create("area-devices-modal", {
		title: `<i class="ph ph-map-trifold normalize"></i> ${area.display_name}`,
		body: modal => {
			return `
				<div class="loader"></div>
				<div class="devices-container h-100"></div>
			`;
		},
		actions: modal => {
			const btnCancel = Helper.template.createElement("button", {
				class: "btn btn-primary"
			}, "Close");

			const btnRebootAll = Helper.template.createElement("button", {
				class: "btn btn-warning with-icon btn-reboot-all"
			}, `<i class="ph ph-arrow-clockwise"></i> Reboot All`);

			btnCancel.addEventListener("click", e => {
				modal.close();
			});

			btnRebootAll.addEventListener("click", e => {
				if(btnRebootAll.getAttribute("disabled")) {
					return;
				}

				Helper.states.btnLoadingState(btnRebootAll, true);
				confirmPopup(
					`Are you sure you want to reboot all devices from <b>${area.display_name}</b>?`, 
					() => {
						sh_api.areas.reboot_devices(
							area.id,
							(err, data, meta) => {
								
								Helper.states.btnLoadingState(btnRebootAll, false);

								if(data) {
									console.log("Was rebooted all devices");

									Toasts.createSuccess(
										"Rebooted all devices",
										`Area: <b>${area.display_name}</b>`
									).show();
								} else {
									Toasts.createDanger(
										"Rebooted fail",
										`Area: <b>${area.display_name}</b>`
									).show();
								}
							}
						);
				}, 
				() => {
					Helper.states.btnLoadingState(btnRebootAll, false);
					console.log("CANCELED");
				});
			});

			return [ btnCancel, btnRebootAll ];
		},
		onready: modal => {
			const devicesContainer = modal.querySelector(".devices-container");
			const loader = modal.querySelector(".loader");

			sh_api.areas.devices(area.id, (err, data, meta) => {
				console.log("sh_api.areas.devices", data);

				function prepareDevicesData(data) {
					if(!data) {
						return [];
					}

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

						preparedData.push({
							deviceNaming: `
								<div class="device-name">${device.name}</div>
								<div class="device-alias mt-2 text-muted"><i class="ph ph-link-simple-break normalize"></i> ${device.alias}</div>
							`,
							status: Helper.template.connectionStatusBadge(device.connection_status),
							state: `<div 
									class="device-state-container"
									data-device-id="${device.id}"
									data-device-type="${device.type}"
								></div>
							`,
							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;
				}

				const devices = prepareDevicesData(data?.data);
				if(devices.length) {
					devicesContainer.innerHTML = Helper.template.table(
						"", 
						{
							deviceNaming: "Device", 
							status: "Status", 
							state: "State", 
							actions: "Actions"
						},
						devices,
						`<span class="table-meta">Total: <span class="total">${devices.length}</span> devices</span>`
					);
				} else {
					devicesContainer.innerHTML = Helper.template.emptyHereHTML();
					modal.querySelector(".btn-reboot-all").remove();
				}

				devicesContainer.querySelectorAll(".reboot-btn").forEach(rebootBtn => {
					rebootBtn.addEventListener("click", e => {
						if(rebootBtn.getAttribute("disabled")) {
							return ;
						}

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

				devicesContainer.querySelectorAll(".device-state-container").forEach(container => {
					container.append(deviceStateComponent(
						sh_api, 
						container.dataset.deviceId, 
						container.dataset.deviceType
					));
				});

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

				loader.remove();

				console.log("devices", devices);
			});
		}
	});
}