import { rebootDeviceBtnHandler } from "./devices-funcs.js";
import { placeInArea } from "../areas/areas-placeto-component.js";
import deviceStateComponent from "./device-state-component.js";

function initEditedFields(sh_api, device, modal) {
	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) {
					DataProvider.invalidate(`raw.devices.${device.id}`);
					Screens.reinit();
				}
			});
		});
	}
}

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

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

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

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

						return `<span class="badge ${map[value]}">${value}</span>`
					},
					connection_status: 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');

			const buttonResetup = Helper.template.createElement("button", {
				class: "btn btn-secondary with-icon"
			}, '<i class="ph ph-gear"></i> ReSetup');

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

			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");

								DataProvider.invalidate(`raw.devices.${device.id}`);
								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");
				});
			});

			buttonResetup.dataset.deviceId = device.id;

			buttonResetup.addEventListener("click", e => {
				const deviceId = buttonResetup.dataset.deviceId;

				Helper.states.btnLoadingState(buttonResetup, true);
				confirmPopup(
					"Are you sure you want to repeat setup device?", 
					() => {
						sh_api.devices.resetup({
							device_id: deviceId
						},
						(err, data, meta) => {
							
							Helper.states.btnLoadingState(buttonResetup, false);

							DataProvider.invalidate(`raw.devices.${device.id}`);
							modal.close();
							Screens.reinit();

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

			buttonReset.dataset.deviceId = device.id;

			buttonReset.addEventListener("click", e => {
				const deviceId = buttonReset.dataset.deviceId;

				Helper.states.btnLoadingState(buttonReset, true);
				confirmPopup(
					"Are you sure you want to RESET device?", 
					() => {
						sh_api.devices.reset({
							device_id: deviceId
						},
						(err, data, meta) => {
							
							Helper.states.btnLoadingState(buttonReset, false);

							DataProvider.invalidate(`raw.devices.${device.id}`);
							modal.close();
							Screens.reinit();

							setTimeout(() => {
								Toasts.createSuccess(
									"Success",
									`Device Id: ${device.name}<br>
									Alias: <b>${device.alias}</b>`
								).show();
							}, 300);
						}
					);
				}, 
				() => {
					Helper.states.btnLoadingState(buttonReset, false);
				});
			});

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

			modal.querySelector(".state-container").append(deviceStateComponent(sh_api, device.id, device.type));

			initEditedFields(sh_api, device, modal);
			
		}
	});
}