/*! grafana - v4.2.0 - 2017-03-24
 * Copyright (c) 2017 Torkel Ödegaard; Licensed Apache-2.0 */

System.register(["lodash","moment","app/core/utils/datemath","./metric_find_query"],function(a,b){"use strict";function c(a,b,c,i,j){function k(a){return a.replace(/[\\^$*+?.()|[\]{}]/g,"\\\\$&")}this.type="prometheus",this.editorSrc="app/features/prometheus/partials/query.editor.html",this.name=a.name,this.supportMetrics=!0,this.url=a.url,this.directUrl=a.directUrl,this.basicAuth=a.basicAuth,this.withCredentials=a.withCredentials,this.lastErrors={},this._request=function(a,b,d){var e={url:this.url+b,method:a,requestId:d};return(this.basicAuth||this.withCredentials)&&(e.withCredentials=!0),this.basicAuth&&(e.headers={Authorization:this.basicAuth}),c.datasourceRequest(e)},this.interpolateQueryExpr=function(a,b,c){if(!b.multi&&!b.includeAll)return a;if("string"==typeof a)return k(a);var e=d.default.map(a,k);return e.join("|")},this.targetContainsTemplate=function(a){return i.variableExists(a.expr)},this.query=function(a){var c=this,e=this,f=this.getPrometheusTime(a.range.from,!1),g=this.getPrometheusTime(a.range.to,!0),h=[],j=[];if(a=d.default.clone(a),d.default.each(a.targets,function(b){if(b.expr&&!b.hide){j.push(b);var d={};d.expr=i.replace(b.expr,a.scopedVars,e.interpolateQueryExpr),d.requestId=a.panelId+b.refId;var k=i.replace(b.interval,a.scopedVars)||a.interval,l=b.intervalFactor||1;b.step=d.step=c.calculateInterval(k,l);var m=Math.ceil(g-f);0!==d.step&&m/d.step>11e3&&(b.step=d.step=Math.ceil(m/11e3)),h.push(d)}}),d.default.isEmpty(h)){var k=b.defer();return k.resolve({data:[]}),k.promise}var l=d.default.map(h,function(a){return c.performTimeSeriesQuery(a,f,g)});return b.all(l).then(function(a){var b=[];return d.default.each(a,function(a,c){if("error"===a.status)throw e.lastErrors.query=a.error,a.error;delete e.lastErrors.query,d.default.each(a.data.data.result,function(a){b.push(e.transformMetricData(a,j[c],f,g))})}),{data:b}})},this.performTimeSeriesQuery=function(a,b,c){if(b>c)throw{message:"Invalid time range"};var d="/api/v1/query_range?query="+encodeURIComponent(a.expr)+"&start="+b+"&end="+c+"&step="+a.step;return this._request("GET",d,a.requestId)},this.performSuggestQuery=function(a){var b="/api/v1/label/__name__/values";return this._request("GET",b).then(function(b){return d.default.filter(b.data.data,function(b){return 1!==b.indexOf(a)})})},this.metricFindQuery=function(a){if(!a)return b.when([]);var c;try{c=i.replace(a,{},this.interpolateQueryExpr)}catch(a){return b.reject(a)}var d=new g.default(this,c,j);return d.process()},this.annotationQuery=function(a){var c=a.annotation,e=c.expr||"",f=c.tagKeys||"",g=c.titleFormat||"",h=c.textFormat||"";if(!e)return b.when([]);var j;try{j=i.replace(e,{},this.interpolateQueryExpr)}catch(a){return b.reject(a)}var k={expr:j,step:"60s"},l=this.getPrometheusTime(a.range.from,!1),m=this.getPrometheusTime(a.range.to,!0),n=this;return this.performTimeSeriesQuery(k,l,m).then(function(a){var b=[];return f=f.split(","),d.default.each(a.data.data.result,function(a){var e=d.default.chain(a.metric).filter(function(a,b){return d.default.includes(f,b)}).value();d.default.each(a.values,function(d){if("1"===d[1]){var f={annotation:c,time:1e3*Math.floor(d[0]),title:n.renderTemplate(g,a.metric),tags:e,text:n.renderTemplate(h,a.metric)};b.push(f)}})}),b})},this.testDatasource=function(){return this.metricFindQuery("metrics(.*)").then(function(){return{status:"success",message:"Data source is working",title:"Success"}})},this.calculateInterval=function(a,b){var c=a.match(h),d=e.default.duration(parseInt(c[1]),c[2]),f=d.asSeconds();return f<1&&(f=1),Math.ceil(f*b)},this.transformMetricData=function(a,b,c,e){var f=[],g=null;g=this.createMetricLabel(a.metric,b);var h=1e3*parseInt(b.step),i=1e3*c;d.default.each(a.values,function(a){var b=parseFloat(a[1]);d.default.isNaN(b)&&(b=null);for(var c=1e3*a[0],e=i;e<c;e+=h)f.push([null,e]);i=c+h,f.push([b,c])});for(var j=1e3*e,k=i;k<=j;k+=h)f.push([null,k]);return{target:g,datapoints:f}},this.createMetricLabel=function(a,b){return d.default.isUndefined(b)||d.default.isEmpty(b.legendFormat)?this.getOriginalMetricName(a):this.renderTemplate(i.replace(b.legendFormat),a)||"{}"},this.renderTemplate=function(a,b){var c=/\{\{\s*(.+?)\s*\}\}/g;return a.replace(c,function(a,c){return b[c]?b[c]:c})},this.getOriginalMetricName=function(a){var b=a.__name__||"";delete a.__name__;var c=d.default.map(d.default.toPairs(a),function(a){return a[0]+'="'+a[1]+'"'}).join(",");return b+"{"+c+"}"},this.getPrometheusTime=function(a,b){return d.default.isString(a)&&(a=f.parse(a,b)),Math.ceil(a.valueOf()/1e3)}}c.$inject=["instanceSettings","$q","backendSrv","templateSrv","timeSrv"];b&&b.id;a("PrometheusDatasource",c);var d,e,f,g,h;return{setters:[function(a){d=a},function(a){e=a},function(a){f=a},function(a){g=a}],execute:function(){h=/(\d+)(ms|s|m|h|d|w|M|y)/}}});