import {randId} from "./random"; import {nullish} from "./null"; import {fetchGet, fetchPatch} from "./fetcher"; const localData = {}; const callbacks = []; export function subscribeToLight(lightId, callback) { const callbackId = randId(); callbacks.push({callbackId, lightId, callback}); if (lightId >= 0) { dispatch(); fetchOne(lightId); } else { dispatch(); fetchAll(); } } export function unsubscribeFromLight(callbackId) { const callback = callbacks.find(c => c !== null && c.callbackId === callbackId); const index = callbacks.indexOf(callback); callbacks[index] = null; } export function changeColor(lightId, newColor, newBrightness, newPower) { const light = localData[lightId]; if (nullish(light)) { return; } const oldBrightness = light.brightness; const oldPower = light.on; const oldColor = light.color; light.color = newColor; light.brightness = newBrightness; light.on = newPower; dispatch(); fetchPatch(`/light/${lightId}`, { color: newColor, brightness: newBrightness, on: newPower, }).then(({data, error}) => { if (error !== null) { light.color = oldColor; light.brightness = oldBrightness; light.on = oldPower; dispatch(); return; } localData[lightId] = data; dispatch(); }); } export function changeLight(lightId, name, groupId) { const light = localData[lightId]; if (nullish(light)) { return; } const oldName = light.name; const oldGroupId = light.groupId; light.name = name; light.groupId = groupId; dispatch(); console.log({name,groupId}); fetchPatch(`/light/${lightId}`, { name: name, groupId: groupId, }).then(({data, error}) => { if (error !== null) { light.name = oldName; light.groupId = oldGroupId; dispatch(); return; } localData[lightId] = data; dispatch(); }); } function fetchAll() { fetchGet(`/light/`).then(({data, error}) => { if (error === null) { handleLights(data); } }); } function fetchOne(id) { fetchGet(`/light/${id}`).then(({data, error}) => { if (error === null) { handleLight(data); } }); } function handleLights(lights) { lights.forEach(l => handleLight(l)); for (let key in localData) { if (localData.hasOwnProperty(key) && nullish(lights.find(l => l.id === parseInt(key, 10)))) { delete localData[key]; } } dispatch(lights); } function handleLight(light) { localData[light.id] = light; dispatch(light); } function dispatch(data = null) { if (data === null) { data = Object.values(localData); } if (Array.isArray(data)) { callbacks .filter(c => c !== null) .filter(c => c.lightId === -1) .forEach(c => c.callback(data)); } else { callbacks .filter(c => c !== null) .filter(c => c.lightId === data.id) .forEach(c => c.callback(data)); } }