/*! grafana - v3.0.4 - 2016-06-01
 * Copyright (c) 2016 Torkel Ödegaard; Licensed Apache-2.0 */

define(["angular","lodash","../core_module","app/core/config"],function(a,b,c,d){"use strict";c["default"].service("backendSrv",["$http","alertSrv","$timeout",function(a,c,e){var f=this;this.get=function(a,b){return this.request({method:"GET",url:a,params:b})},this["delete"]=function(a){return this.request({method:"DELETE",url:a})},this.post=function(a,b){return this.request({method:"POST",url:a,data:b})},this.patch=function(a,b){return this.request({method:"PATCH",url:a,data:b})},this.put=function(a,b){return this.request({method:"PUT",url:a,data:b})},this._handleError=function(a){return function(){if(!a.isHandled){var d=a.data||{message:"Unexpected error"};if(b.isString(d)&&(d={message:d}),422===a.status)throw c.set("Validation failed",d.message,"warning",4e3),d;throw d.severity="error",a.status<500&&(d.severity="warning"),d.message&&c.set("Problem!",d.message,d.severity,1e4),d}}},this.request=function(b){b.retry=b.retry||0;var g=0===b.url.indexOf("/"),h=0===b.retry;return g&&!b.hasSubUrl&&(b.url=d.appSubUrl+b.url,b.hasSubUrl=!0),a(b).then(function(a){return"GET"!==b.method&&a&&a.data.message&&c.set(a.data.message,"","success",3e3),a.data},function(a){if(401===a.status&&h)return f.loginPing().then(function(){return b.retry=1,f.request(b)});throw e(f._handleError(a),50),a})},this.datasourceRequest=function(c){c.retry=c.retry||0;var d=0===c.url.indexOf("/"),e=0===c.retry;return a(c).then(null,function(a){if(d&&e&&401===a.status)return f.loginPing().then(function(){return c.retry=1,f.datasourceRequest(c)});throw b.isString(a.data)&&500===a.status&&(a.data={error:a.statusText}),!a.data.message&&b.isString(a.data.error)&&(a.data.message=a.data.error),a})},this.loginPing=function(){return this.request({url:"/api/login/ping",method:"GET",retry:1})},this.search=function(a){return this.get("/api/search",a)},this.getDashboard=function(a,b){return this.get("/api/dashboards/"+a+"/"+b)},this.saveDashboard=function(a,b){return b=b||{},this.post("/api/dashboards/db/",{dashboard:a,overwrite:b.overwrite===!0})}}])});