/*! grafana - v3.1.0 - 2016-07-18
 * Copyright (c) 2016 Torkel Ödegaard; Licensed Apache-2.0 */

System.register(["lodash","moment","app/core/utils/datemath","./metric_find_query"],function(a){function b(a,b,h,i,j){function k(a){return a.replace(/[\\^$*+?.()|[\]{}]/g,"\\\\$&")}function l(a,b){return c["default"].isString(a)&&(a=e.parse(a,b)),Math.ceil(a.valueOf()/1e3)}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,c){var d={url:this.url+b,method:a,requestId:c};return(this.basicAuth||this.withCredentials)&&(d.withCredentials=!0),this.basicAuth&&(d.headers={Authorization:this.basicAuth}),h.datasourceRequest(d)},this.interpolateQueryExpr=function(a,b,d){if(!b.multi&&!b.includeAll)return a;if("string"==typeof a)return k(a);var e=c["default"].map(a,k);return e.join("|")};this.query=function(a){var d=this,e=l(a.range.from,!1),f=l(a.range.to,!0),g=[],h=[];if(a=c["default"].clone(a),c["default"].each(a.targets,c["default"].bind(function(b){if(b.expr&&!b.hide){h.push(b);var c={};c.expr=i.replace(b.expr,a.scopedVars,d.interpolateQueryExpr),c.requestId=a.panelId+b.refId;var j=b.interval||a.interval,k=b.intervalFactor||1;b.step=c.step=this.calculateInterval(j,k);var l=Math.ceil(f-e);0!==c.step&&l/c.step>11e3&&(b.step=c.step=Math.ceil(l/11e3)),g.push(c)}},this)),c["default"].isEmpty(g)){var j=b.defer();return j.resolve({data:[]}),j.promise}var k=c["default"].map(g,c["default"].bind(function(a){return this.performTimeSeriesQuery(a,e,f)},this));return b.all(k).then(function(a){var b=[];return c["default"].each(a,function(a,g){if("error"===a.status)throw d.lastErrors.query=a.error,a.error;delete d.lastErrors.query,c["default"].each(a.data.data.result,function(a){b.push(d.transformMetricData(a,h[g],e,f))})}),{data:b}})},this.performTimeSeriesQuery=function(a,b,c){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 c["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(d){return b.reject(d)}var e=new f["default"](this,c,j);return e.process()},this.annotationQuery=function(a){var d=a.annotation,e=d.expr||"",f=d.tagKeys||"",g=d.titleFormat||"",h=d.textFormat||"";if(!e)return b.when([]);var j;try{j=i.replace(e,{},this.interpolateQueryExpr)}catch(k){return b.reject(k)}var m={expr:j,step:"60s"},n=l(a.range.from,!1),o=l(a.range.to,!0),p=this;return this.performTimeSeriesQuery(m,n,o).then(function(a){var b=[];return f=f.split(","),c["default"].each(a.data.data.result,function(a){var e=c["default"].chain(a.metric).filter(function(a,b){return c["default"].contains(f,b)}).value();c["default"].each(a.values,function(c){if("1"===c[1]){var f={annotation:d,time:1e3*Math.floor(c[0]),title:p.renderTemplate(g,a.metric),tags:e,text:p.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(g),e=d["default"].duration(parseInt(c[1]),c[2]),f=e.asSeconds();return f<1&&(f=1),Math.ceil(f*b)},this.transformMetricData=function(a,b,d,e){var f=[],g=null;g=this.createMetricLabel(a.metric,b);var h=1e3*parseInt(b.step),i=1e3*d;c["default"].each(a.values,function(a){var b=parseFloat(a[1]);c["default"].isNaN(b)&&(b=null);for(var d=1e3*a[0],e=i;e<d;e+=h)f.push([null,e]);i=d+h,f.push([b,d])});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 c["default"].isUndefined(b)||c["default"].isEmpty(b.legendFormat)?this.getOriginalMetricName(a):this.renderTemplate(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 d=c["default"].map(c["default"].pairs(a),function(a){return a[0]+'="'+a[1]+'"'}).join(",");return b+"{"+d+"}"}}b.$inject=["instanceSettings","$q","backendSrv","templateSrv","timeSrv"];var c,d,e,f,g;return a("PrometheusDatasource",b),{setters:[function(a){c=a},function(a){d=a},function(a){e=a},function(a){f=a}],execute:function(){g=/(\d+)(ms|s|m|h|d|w|M|y)/}}});