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" : "";
			channels += `
				<span class="badge ${channelStateClass}">id${channel.id}: <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]}">id${channel.id}: <b>${channel.indicator}</b></span>
			`;
		}

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

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

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

	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("deviceStatusComponent", `DeviceID ${deviceId}`);
		}

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

	return component;
}