#
# The docker_builds collection contains the output and meta data related to a docker build
# of a Lever service.
# Builds may be attached to a `Release`. See `devPortal/Release` for details.
#
# @property branchName [String] the branch name to build
# @property commitSha [String] the commit sha of the build
# @property createdAt [Number] the time the DockerBuild was built
# @property consoleOutput [String] the console output of the build
# @property dockerSha [String] the docker sha of the build
# @property npmLsOutput [String] npm ls output of the build
# @property projectId [uuid] id of the build's project
# @property releaseCandidateId [uuid] id of the build's release candidate
# @property serviceName [String] the name of the service
# @property updatedAt [Number] when this Release was updated
module.exports = (Model) ->
  DockerBuild = Model.collection 'DockerBuild', 'docker_builds'

  # Build a DockerBuild document
  #
  # @param options [Object] provider of @options below
  # @option branchName [String] the branch name to build
  # @option commitSha [String] the commit sha of the build
  # @option createdAt [Number] the time the DockerBuild was built
  # @option consoleOutput [String] the console output of the build
  # @option dockerSha [String] the docker sha of the build
  # @option npmLsOutput [String] npm ls output of the build
  # @option projectId [uuid] id of the build's project
  # @option releaseCandidateId [uuid] id of the build's release
  # @option serviceName [String] the name of the service
  # @option updatedAt [Number] when this Release was updated
  DockerBuild.build = (options) ->
    throw new Error 'options missing' unless options

    dockerBuild =
      repo: options.repo
      branchName: options.branchName || 'master'
      commitSha: options.commitSha
      consoleOutput: options.consoleOutput
      createdAt: Date.now()
      imageId: options.imageId
      npmLsOutput: options.npmLsOutput
      projectId: options.projectId
      releaseCandidateId: options.releaseCandidateId
      updatedAt: Date.now()
      userId: options.userId || @model.get('_session.userId')
      options:
        tag: options.tag

    throw new Error 'Cannot create a build without providing a repo' unless dockerBuild.repo

    return dockerBuild

  # Adds a new docker build to the collection
  # See DockerBuild.build for options definition
  #
  # @param options [Object] options for building the release
  DockerBuild.addNew = (options) ->
    dockerBuild = @build options
    return @add dockerBuild
