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

define(["angular","lodash"],function(a,b){"use strict";var c=a.module("grafana.services");c.service("dynamicDashboardSrv",function(){var c=this;this.init=function(a){a.snapshot||(this.iteration=(new Date).getTime(),this.process(a))},this.update=function(a){a.snapshot||(this.iteration=this.iteration+1,this.process(a))},this.process=function(a){if(0!==a.templating.list.length){this.dashboard=a;var c,d,e,f;for(c=0;c<this.dashboard.rows.length;c++){if(e=this.dashboard.rows[c],e.repeat)this.repeatRow(e,c);else if(e.repeatRowId&&e.repeatIteration!==this.iteration){this.dashboard.rows.splice(c,1),c-=1;continue}for(d=0;d<e.panels.length;d++)if(f=e.panels[d],f.repeat)this.repeatPanel(f,e);else if(f.repeatPanelId&&f.repeatIteration!==this.iteration)e.panels=b.without(e.panels,f),d-=1;else{if(e.repeat||e.repeatRowId)continue;b.isEmpty(f.scopedVars)||f.repeatIteration===this.iteration||(f.scopedVars={})}}}},this.getRowClone=function(b,c,d){if(0===c)return b;var e,f,g,h,i=d+1;for(e=0;e<this.dashboard.rows.length;e++)if(g=this.dashboard.rows[e],g.repeatRowId===i&&g.repeatIteration!==this.iteration){h=g;break}if(!h)for(h=a.copy(b),this.dashboard.rows.splice(d+c,0,h),e=0;e<h.panels.length;e++)f=h.panels[e],f.id=this.dashboard.getNextPanelId();return h.repeat=null,h.repeatRowId=i,h.repeatIteration=this.iteration,h},this.repeatRow=function(a,d){var e=this.dashboard.templating.list,f=b.findWhere(e,{name:a.repeat});if(f){var g,h,i,j;g="All"===f.current.text?f.options.slice(1,f.options.length):b.filter(f.options,{selected:!0}),b.each(g,function(b,e){for(h=c.getRowClone(a,e,d),h.scopedVars={},h.scopedVars[f.name]=b,i=0;i<h.panels.length;i++)j=h.panels[i],j.scopedVars={},j.scopedVars[f.name]=b},this)}},this.getPanelClone=function(b,c,d){if(0===d)return b;var e,f,g,h;for(e=0;e<c.panels.length;e++)if(g=c.panels[e],g.repeatIteration!==this.iteration&&g.repeatPanelId===b.id){h=g;break}return h||(h={id:this.dashboard.getNextPanelId()},c.panels.push(h)),f=h.id,a.copy(b,h),h.id=f,h.repeatIteration=this.iteration,h.repeatPanelId=b.id,h.repeat=null,h},this.repeatPanel=function(a,d){var e=this.dashboard.templating.list,f=b.findWhere(e,{name:a.repeat});if(f){var g;g="All"===f.current.text?f.options.slice(1,f.options.length):b.filter(f.options,{selected:!0}),b.each(g,function(b,e){var h=c.getPanelClone(a,d,e);h.span=Math.max(12/g.length,a.minSpan),h.scopedVars=h.scopedVars||{},h.scopedVars[f.name]=b})}}})});