const request = require('request-promise-native')
const { logger } = require('./utils')

const organization = process.env.BITBUCKET_REPO_OWNER || 'viewdo'
const bitbucket_api_url = `https://api.bitbucket.org/2.0/repositories/${organization}`

const runPipeline = (user, password, repository, custom_build, branch = 'master') => {
  let target = {
    type: "pipeline_ref_target",
    ref_type: "branch",
    ref_name: branch
  }
  if(custom_build)
    target.selector = {
      type: "custom",
      pattern: custom_build
    }

  return request.post(`${bitbucket_api_url}/${repository}/pipelines/`, {
    body: {
      target
    },
    auth: {
      user,
      password
    },
    json: true
  })
}


const setVariable = async (user, password, repository, key, value) => {

  let variable_list = await request(`${bitbucket_api_url}/${repository}/pipelines_config/variables/?pagelen=100`,{
      auth: {
        user,
        password
      },
      json: true
    })
    .then(r => r.values)

  // console.dir(variable_list.map(v => v.key))

  if(variable_list.map(v => v.key).includes(key)) {
    // exists, update it
    logger(`Updating variable ${key}`)
    let uuid = variable_list.filter(v => v.key == key)[0].uuid
    await request.put(`${bitbucket_api_url}/${repository}/pipelines_config/variables/${uuid}`,
    {
      body: {
        key,
        value,
        secured: false
      },
      json: true,
      auth: {
        user,
        password
      }
    })

  } else {
    // doesn't exist, create it
    logger(`Creating variable ${key}`)
    await request.post(`${bitbucket_api_url}/${repository}/pipelines_config/variables/`,
    {
      body: {
        key,
        value,
        secured: false
      },
      json: true,
      auth: {
        user,
        password
      }
    })
  }

  logger(`Variable ${key} set to ${value} in repository ${repository}`)
  return 0

}

module.exports = {
  runPipeline,
  setVariable
}