util = require '../util'
Kue = require 'kue'

module.exports = class Master
  constructor: (@model, @kue) ->
    console.log 'new master created'
  build: (repo, branch='master', options={}, cb) ->
    console.log 'Adding build job', repo, branch, options
    buildId = @model.DockerBuild.addNew
      repo: repo
      branchName: branch
      tag: options.tag
      userId: options.userId
      releaseCandidateId: options.releaseCandidateId
      projectId: options.projectId

    # TOOD: Remove or make optional verbose logging
    console.log 'created build'
    util.log @model.DockerBuild.get(buildId)

    options.repo = repo
    options.branch = branch
    # TODO: Findout why when using shareDB we need to introduce a delay
    # to ensure the build is available on the other process
    @model.whenNothingPending =>
      @_addJob buildId, 'build', options, cb

  stop: (jobId, cb) ->
    Kue.Job.get jobId, (err, job) ->
      return cb err if err
      job.remove (err) ->
        return cb err if err
        console.log "Job #{jobId} removed"
        cb()

  push: (buildId, cb) ->
    _addJob buildId, 'push', null, cb

  deploy: (buildId, target, cb) ->
    _addJob buildId, 'deploy', {target}, cb

  _addJob: (buildId, action, options={}, cb = -> ) ->
    job = @kue.create 'buildTask',
      title: "Building #{options.repo}:#{options.branch}"
      action: action
      buildId: buildId
      repo: options.repo
      branch: options.branch
      tag: options.tag
      userId: options.userId
      releaseCandidateId: options.releaseCandidateId
      projectId: options.projectId
      options:
        buildOnly: options.buildOnly

    job.save (err) ->
      if err
        console.error 'Error saving job', err
        return cb err
      console.log 'created job', job.id, job.data
      cb null, job.id
