const renderingByType = {
	relay: (alias, deviceResp) => {
		let channels = "";
		for(let channel of deviceResp.channels) {
			const channelState = channel.state == "off" ? "OFF" : "ON";
			const channelStateClass = channel.state == "on" ? "badge-success" : "";
			const chId = deviceResp.channels.length > 1 ? `${channel.id}:` : "";
			channels += `
				<span class="badge ${channelStateClass}">${chId}<b>${channelState}</b></span>
			`;
		}

		return `<div class="channels f-grid g-2">${channels}</div>`;
	},

	button: (alias, deviceResp) => {
		const channelClassMap = {
			enabled: "badge-success",
			disabled: "",
			mute: "badge-primary-outline",
			waiting: "badge-warning",
			error: "badge-error"
		};

		let channels = "";
		for(let channel of deviceResp.channels) {
			channels += `
				<span class="badge ${channelClassMap[channel.indicator]}">${channel.id}:<b>${channel.indicator}</b></span>
			`;
		}

		return `<div class="channels f-grid g-2">${channels}</div>`;
	}
};

function initEventHandlers(component) {
	component.addEventListener("click", e => {
		e.currentTarget.deviceStateComponent.create();
	});
}

function stateRendering(deviceType, deviceAlias, deviceResponse) {
	return typeof renderingByType[deviceType] != "undefined"
		? renderingByType[deviceType](deviceAlias, deviceResponse)
		: "Unknown device type<br>" + JSON.stringify(deviceResponse);
}

export default function deviceStateComponent(sh_api, deviceId, deviceType) {
	const component = Helper.template.createElement("div", {
		class: "component device-state-component"
	}, "");

	component.deviceStateComponent = {
		create: () => {
			component.innerHTML = Helper.template.circleLoaderHTML();

			sh_api.devices.status(deviceId, (err, resp, meta) => {
				console.log("sh_api.devices.status", err, resp);

				if(!resp) {
					component.innerHTML = `
						<span class="badge badge-error"><i class="ph ph-warning-octagon fs-lg normalize"></i> Loading Error</span>
					`;
					return console.error("deviceStateComponent", `DeviceID ${deviceId}`);
				}

				component.innerHTML = stateRendering(deviceType, resp.data.device.alias, resp.data.device.device_response);
				initEventHandlers(component);
			});
		}
	}

	component.deviceStateComponent.create();

	return component;
}