/*! phoscon-app 2024-10-07 */

"use strict";function bbInitThermostats(){app.api.on("event",function(e){if("thermostats"!==e.r)return;if("added"===e.e){app.thermostats.get(e.sensor.id);return void app.thermostats.fetch()}if("changed"!==e.e)return;let s=app.thermostats.get(e.id);if(s){var args={};args.ec=s.get("ec")||0,_.map(e,function(val,key){["state","config","name"].forEach(a=>{key===a&&(args.ec++,args[a]=val)})}),s.set(args),setTimeout(()=>s.fetch(),0)}}),app.Thermostat=Backbone.Model.extend({sync:function(method,model,options){},rename:function(name){this.save({name:name},{patch:!0})},initialize:function(){if(!this.has("type")||0!==this.get("type").indexOf("CLIP")){var uuid=this.get("uniqueid");if(uuid){var p=uuid.split("-");this.set({mac:p[0],endpoint:p[1]})}}}}),app.ThermostatCollection=Backbone.Collection.extend({name:"thermostats",model:app.Thermostat});var SensorScan=Backbone.Model.extend({url:"//"+app.session.gw+"/api/"+app.apikey+"/sensors/new",isActive:function(){return this.has("lastscan")&&"active"===this.get("lastscan")},start:function(){this.clear(),Backbone.sync("create",this,{url:"//"+app.session.gw+"/api/"+app.apikey+"/sensors"})}});function createThermostatFromSensor(s){if(!s.modelid)return;var sensorAttributes=function(th){let mac=th.uniqueid.split("-")[0]||-1,state=app.sensors.filter(sensor=>-1!==sensor.get("uniqueid").indexOf(mac)).map(s=>s.get("state"));return Object.assign({},...state)}(s);Object.assign(s.state,sensorAttributes);let mac=s.uniqueid.split("-")[0],sensor=_.clone(s);return app.thermostats.add({...sensor,mac:mac})}function addSensor(sensor){if(sensor.isNew())setTimeout(()=>addSensor(sensor),100);else if(-1!=sensor.get("type").indexOf("Thermostat")){var th=createThermostatFromSensor(_.clone(sensor.attributes));app.api.trigger("thermostat-added",th)}}app.thermostats=new app.ThermostatCollection,app.sensorScan=new SensorScan,app.sensors.on("remove",function(sensor,options){let th=app.thermostats.find(th=>th.attributes.uniqueid===sensor.attributes.uniqueid)||void 0;th&&th.destroy()}),app.sensors.on("change",function(sensor,options){var th=app.thermostats.find(p=>-1!==sensor.get("uniqueid").indexOf(p.get("mac")));if(th){var stateChanges=sensor.changedAttributes();stateChanges.name&&th.set({name:stateChanges.name}),stateChanges.state&&th.set({state:stateChanges.state}),stateChanges.config&&th.set({config:stateChanges.config})}}),app.sensors.on("add",addSensor),app.sensors.forEach(addSensor)}