Newer
Older
smart-home-server / webclient / src / js / components / screens / devices / device-details-popup.js
import { rebootDeviceBtnHandler } from "./devices-funcs.js";
import { placeInArea } from "../areas/areas-placeto-component.js";
import deviceStatusComponent from "./device-status-component.js";

export function deviceDetailsPopup(device, sh_api) {
	console.log(device);

	return Modals.create("device-popup", {
		title: `Device ${device.name}`,
		body: modal => {
			/* alias, area_id, connection_state, create_at, description, device_id, 
			firmware_version, id, ip, last_contact, mac, name, state, type, update_at */

			const fieldClassMap = {
				area_id: "place-in-area-component-container",
				ip: "device-ip",
				status: "status-container",
				name: "display-name",
				description: "description",
				alias: "alias-view-container"
			};

			const wrapToContainer = (field, value) => {
				const map = {
					ip: `<code>{{value}}</code>`,
					state: value => {
						const map = {
							active: "badge-success",
							removed: "badge-error",
							freezed: "badge-warning" 
						};

						return `<span class="badge ${map[value]}">${value}</span>`
					},
					connection_state: value => {
						const badgeClass = value == "active" ? "badge-success" : "badge-warning";
						return `<span class="badge ${badgeClass}">${value}</span>`
					},
					mac: `<code>{{value}}</code>`,
					alias: `<i class="ph ph-link-simple-break"></i> <span class="alias">{{value}}</span>`,
					device_id: `<code>{{value}}</code>`,
					last_contact: value => Helper.unification.timeAgo(value),
					create_at: value => Helper.unification.formatDate(value),
					update_at: value => Helper.unification.formatDate(value),
				}

				return map[field] 
					? (typeof map[field] == "function" ? map[field](value) : map[field].replaceAll("{{value}}", value))
					: value; 
			}

			let deviceProperties = "";
			for(let field in device) {
				let fieldValueClass = fieldClassMap[field] ?? "";

				deviceProperties += `
					<tr class="table-row">
						<th>${field}: </th>
						<td class="${fieldValueClass}">${wrapToContainer(field, device[field])}</td>
					</tr>
				`;
			}

			return `
				<div class="block">
					<table class="table" style="border: 0">
						<tbody class="table-body">
							${deviceProperties}
						</tbody>
					</table>
				</div>
			`;
		},
		actions: modal => {
			const buttonCancel = Helper.template.createElement("button", {
				class: "btn btn-primary"
			}, "Close");

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

			const buttonRemove = Helper.template.createElement("button", {
				class: "btn btn-danger with-icon"
			}, '<i class="ph ph-trash"></i> Remove');

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

			buttonReboot.dataset.deviceId = device.id;
			buttonReboot.dataset.deviceName = device.name;
			buttonReboot.dataset.deviceAlias = device.alias;

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

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

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

				Helper.states.btnLoadingState(buttonRemove, true);
				confirmPopup(
					"Are you sure you want to remove this device?", 
					() => {
						sh_api.devices.remove(
							device.id,
							(err, data, meta) => {
								
								Helper.states.btnLoadingState(buttonRemove, false);
								console.log("Was removed");

								modal.close();
								Screens.reinit();

								setTimeout(() => {
									Toasts.createSuccess(
										"Removed",
										`
										Device: ${device.name}<br>
										Alias: <b>${device.alias}</b><br>
										IP: <b>${device.ip}</b>
										`
									).show();
								}, 300);
							}
						);
				}, 
				() => {
					Helper.states.btnLoadingState(buttonRemove, false);
					console.log("CANCELED");
				});
			});

			return [ buttonCancel, buttonReboot, buttonRemove ];
		},
		onready: modal => {
			placeInArea(
				sh_api,
				modal.querySelector(".place-in-area-component-container"),
				"device",
				device.id,
				device.area_id
			);

			modal.querySelector(".status-container").append(deviceStatusComponent(sh_api, device.id, device.type));

			const editedFields = [
				{
					payloadFieldName: "name",
					selector: ".display-name",
					methName: "update_name",
					originalValue: device.name,
					isMultiString: false
				},
				{
					payloadFieldName: "description",
					selector: ".description",
					methName: "update_description",
					originalValue: device.description,
					isMultiString: true
				},
				{
					payloadFieldName: "new_alias",
					selector: ".alias",
					methName: "update_alias",
					originalValue: device.alias,
					isMultiString: false
				},
			];

			for(let editedField of editedFields) {
				const edit = editableString(modal.querySelector(editedField.selector));
				edit.editableString.onChange(component => {
					const payload = {
						device_id: device.id,
					};

					payload[editedField.payloadFieldName] = component.value;

					sh_api.devices[editedField.methName](payload, (err, resp, meta) => {
						if(err || !resp || !resp.status) {
							console.error(`sh_api.devices.${editedField.methName}`, err);
							edit.editableString.setValue(editedField.originalValue);

							return Toasts.createError(
								err?.message ?? "Error updating", 
								err.raw?.msg ?? `Error of ${editedField.payloadFieldName} updating`
							).show();
						}

						if(resp.status == true) {
							Screens.reinit();
						}
					});
				});
			}
			

			// const editName = editableString(modal.querySelector(".display-name"));
			// editName.editableString.onChange(component => {
			// 	sh_api.devices.update_name({
			// 		device_id: device.id,
			// 		name: component.value
			// 	}, (err, resp, meta) => {
			// 		if(err || !resp) {
			// 			console.error("sh_api.devices.update_name", err);
			// 			editName.editableString.setValue(device.name);

			// 			return Toasts.createError(
			// 				err.message ?? "Error updating", 
			// 				err.raw.msg ?? "Error of device name updating"
			// 			).show();
			// 		}

			// 		if(resp.status == true) {
			// 			Screens.reinit();
			// 		}
			// 	});
			// });

			// const editDescription = editableString(modal.querySelector(".description"), true);
			// editDescription.editableString.onChange(component => {
			// 	sh_api.devices.update_description({
			// 		device_id: device.id,
			// 		description: component.value
			// 	}, (err, resp, meta) => {
			// 		if(err || !resp) {
			// 			console.error("sh_api.devices.update_description", err);
			// 			editDescription.editableString.setValue(device.description);
 
			// 			return Toasts.createError(
			// 				err.message ?? "Error updating", 
			// 				err.raw.msg ?? "Error of device description updating"
			// 			).show();
			// 		}
 
			// 		if(resp.status == true) {
			// 			Screens.reinit();
			// 		}
			// 	});
			// });


			// const editAlias = editableString(modal.querySelector(".alias"));
			// editAlias.editableString.onChange(component => {
			// 	sh_api.devices.update_alias({
			// 		device_id: device.id,
			// 		new_alias: component.value
			// 	}, (err, resp, meta) => {
			// 		if(err || !resp || !resp.status) {
			// 			console.error("sh_api.devices.update_alias", err);
			// 			editAlias.editableString.setValue(device.alias);

			// 			return Toasts.createError(
			// 				err.message ?? "Error updating", 
			// 				err.raw?.msg ?? "Error of alias updating"
			// 			).show();
			// 		}

			// 		if(resp.status == true) {
			// 			Screens.reinit();
			// 		}
			// 	});
			// });
		}
	});
}