(()=>{function t(E,k,t,e,n,b,R,K,M){function i(t,e,n){this.measurements=null,this.dataPoints=null,this.times=null,this.deviceIds=null;var i,r,o=this,a=!1,s=!1;function c(t){return M.listPossibleFast(t).then(m)}function u(){return E.all(_.map(o.deviceIds,d))}function d(t){t=y(t);return R.addListener(e,t,"CREATE",I),E.when(R.start(e,t))}function f(t){return E.when(R.stop(e,y(t)))}function m(t){return r.datapoints?o.dataPoints=_(r.datapoints).filter(P).forEach(p):o.dataPoints=_(r.kpis||(r.kpi?[r.kpi]:[])).map(_.partial(l,t)).map(h).value(),!!_.get(r,"widget.templateUrl","").match("gauge")&&1<o.dataPoints.length&&(o.dataPoints=o.dataPoints.slice(0,1)),E.all(_.map(o.dataPoints,v))}function l(t,e){return e.moId&&_.find(t,{_kpiId:e.moId})||e}function p(t){b.createLocalId(t,"id")}function h(t){t=_.assign({},t,{id:t.moId});return t.id||b.createLocalId(t),t}function v(t){return K.getMeasurement(t,w(t),1).then(_.partial(g,t))}function g(t,e){return o.measurements[t.id]=e[t.series],o.times[t.id]=e.time,e}function I(t,s){var c=s;c&&(_.forEach(c,function(t,a){_.isObjectLike(t)&&_.forEach(t,function(e,t){n=c.source.id,i=a,r=t;var n,i,r,t=_.filter(o.dataPoints,function(t){return w(t)===n&&t.fragment===i&&t.series===r});_.forEach(t,function(t){o.measurements[t.id]=e,o.times[t.id]=s.time})})}),i)&&i()}function P(t){return!("__active"in t)||t.__active}function w(t){return _.get(t,"__target.id")||_.get(r,"device.id")||k.deviceId}function y(t){return"/measurements/".concat(t)}r=_.cloneDeep(t),o.deviceIds=(t=>(t=t.datapoints||t.kpis||[t.kpi],_(t).map(w).uniq().value()))(r),n&&(r.widget=n),this.start=function(){if(a)throw new Error("MostRecentKpi service instance cannot be started more than once");return a=!0,o.refresh().then(u)},this.refresh=function(){return o.dataPoints=[],o.measurements={},o.times={},E.all(_.map(o.deviceIds,c))},this.stop=function(){if(!a)throw new Error("MostRecentKpi service instance cannot be stopped before being started");if(s)throw new Error("MostRecentKpi service instance cannot be stopped more than once");return s=!0,E.all(_.map(o.deviceIds,f))},this.onNotification=function(t){i=t}}return{createInstance:function(t,e,n){return new i(t,e,n)}}}t.$inject=["$q","$routeParams","c8yInventory","c8yMeasurements","c8yDevices","c8yBase","c8yRealtime","c8yKpi","c8yDataPointSvc"],angular.module("c8y.parts.kpi").factory("mostRecentKpiSvc",t)})();