const fs = require('fs')
const YAML = require('yamljs')
const { execShell, getNormalizedBranchName } = require('./utils')

module.exports = (options, logger) => {

  let {
    git_directory = process.env.BITBUCKET_CLONE_DIR || process.cwd(),
  } = options


  let version_file = `${git_directory}/version.yaml`

  let version_info
  if(fs.existsSync(version_file))
    version_info = YAML.load(version_file)

  if(!version_info) {
    let gitVersionScript =
      `docker run -v "${git_directory}:/repo" --rm ` +
      `gittools/gitversion:5.0.0-beta2-65-linux /repo`

    let gitVersionExec = execShell(gitVersionScript, { silent: true })

    let gitVersion = JSON.parse(gitVersionExec.stdout)

    version_info = {
      apiVersion: "view.do/v1",
      kind: "Version",
      metadata: {
        name: gitVersion.BranchName
      },
      spec: {
        metadata: gitVersion
      }
    }

  }

  if(!version_info)
    return {}

  logger('Successfully derived version.'.green)

  let branch = process.env.BITBUCKET_PR_DESTINATION_BRANCH
  || process.env.BITBUCKET_BRANCH
  || version_info.spec.metadata.BranchName
  let namespace = options.namespace || getNormalizedBranchName(branch)
  let build_id = options.build_id || `${getNormalizedBranchName(branch)}-${version_info.spec.metadata.ShortSha}`
  let version = options.version || version_info.spec.metadata.SemVer
  let assembly_version = version_info.spec.metadata.AssemblySemVer || version

  let response = {
    namespace,
    build_id,
    branch,
    version,
    assembly_version
  }

  version_info.spec.data = response

  fs.writeFileSync(version_file, YAML.stringify(version_info, 8, 2))

  fs.appendFileSync(version_file, "---\n")

  logger(JSON.stringify(response, null, 2).green)

  return response
}
