const base64 = require( 'base-64')
const fetch = require( 'node-fetch').default
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 fetch( `${ bitbucket_api_url }/${ repository }/pipelines/`, {
    method: 'POST',
    body: JSON.stringify({
      target
    } ),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
    }
  })
}


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

  let variable_list = await fetch(`${bitbucket_api_url}/${repository}/pipelines_config/variables/?pagelen=100`,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
      }
  } )
  .then(response => response.json())
  .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 fetch( `${ bitbucket_api_url }/${ repository }/pipelines_config/variables/${ uuid }`,
      {
        method:'PUT',
        body: JSON.stringify({
          key,
          value,
          secured: false
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
        }
     })

  } else {
    // doesn't exist, create it
    logger(`Creating variable ${key}`)
    await fetch(`${bitbucket_api_url}/${repository}/pipelines_config/variables/`,
    {
      method:'POST',
      body: JSON.stringify({
        key,
        value,
        secured: false
      }),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
      }
    })
  }

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

}

module.exports = {
  runPipeline,
  setVariable
}