// the leader runs the registry and the git push
var async = require('async')
var Job = require('../tools/job')
var tools = require('../tools')
var flatten = require('etcd-flatten')
var endpoints = require('./endpoints')
var env = require('../tools/env')
var logger = require('../tools/logger')

module.exports = function(config, etcd){

	function loadTags(name, done){
		etcd.get('/stack/' + name + '/tags', {
			recursive:true
		}, function(err, result){
			if(err) return done(err)
			if(!result) return done('no data')

			result = flatten(result.node)

			done(null, result)
		})
	}

	function loadDeploys(name, done){
		etcd.get('/stack/' + name + '/deploys', {
			recursive:true
		}, function(err, result){
			if(err) return done(err)
			if(!result) return done('no data')

			result = flatten(result.node)

			done(null, result)
		})
	}

	function writeStack(stack, done){
		var packet = JSON.stringify(stack.getData())
		etcd.set('/stack/' + stack.id + '/tags/' + stack.tag, packet, done)
	}

	function checkExists(stack, done){

		var key = '/stacks/' + stack.id + '/tags/' + stack.tag
		loadTags(stack.id, function(err, result){
			if(result){
				if(result[key]){
					done(null, result[key])
				}
				else{
					done()
				}
			}
			else{
				done()
			}
		})
		
	}

	return {

		checkExists:checkExists,
		writeStack:writeStack

	}
}

@@ -287,16 +287,53 @@
 logger')
+%0Avar Schedule = require('./schedule')
 %0A%0Amodule
@@ -368,16 +368,56 @@
 etcd)%7B%0A%0A
+%09var schedule = Schedule(config, etcd)%0A%0A
 %09functio
@@ -651,32 +651,570 @@
 esult)%0A%09%09%7D)%0A%09%7D%0A%0A
+%09function loadJobs(name, tags, done)%7B%0A%09%09if(typeof(tags)=='string')%7B%0A%09%09%09tags = %5Btags%5D%0A%09%09%7D%0A%09%09var jobs = %7B%7D%0A%0A%09%09async.forEachSeries(tags, function(tag, nexTag)%7B%0A%09%09%09etcd.get('/proc/' + name + '/' + tag, %7B%0A%09%09%09%09recursive:true%0A%09%09%09%7D, function(err, result)%7B%0A%09%09%09%09if(err) return nexTag(err)%0A%09%09%09%09if(!result) return nextTag('no result')%0A%09%09%09%09result = flatten(result)%0A%09%09%09%09Object.keys(result %7C%7C %7B%7D).forEach(function(key)%7B%0A%09%09%09%09%09jobs%5Bkey%5D = result%5Bkey%5D%0A%09%09%09%09%7D)%0A%09%09%09%09nextTag()%0A%09%09%09%7D)%0A%09%09%7D, function(err)%7B%0A%09%09%09if(err) return done(err)%0A%09%09%09done(null, jobs)%0A%09%09%7D)%0A%09%7D%0A%0A
 %09function loadDe
@@ -1889,16 +1889,58 @@
 %0A%09%09%0A%09%7D%0A%0A
+%09function remove(name, tag, done)%7B%0A%09%09%0A%09%7D%0A%0A
 %09return 
@@ -1992,15 +1992,53 @@
 iteStack
+,%0A%09%09loadJobs:loadJobs,%0A%09%09remove:remove
 %0A%0A%09%7D%0A%7D%0A

remove stack means loading its pids