const shell = require('shelljs')
const fs = require('fs')
const io = require('path')
const envsub = require('envsub')
const {
  findFiles,
  flattenArray,
  requireValue
} = require('./services/utils')
const getVersion = require('./services/version')

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

  let versionInfo = await getVersion(options, logger)

  let {
    assembly_version = process.env.ASSEMBLY_VERSION || versionInfo.assembly_version || '1.0.0.0',
    branch = process.env.VERSION || versionInfo.namespace || requireValue('namespace'),
    build_id = process.env.BUILD_ID || versionInfo.build_id || requireValue('build_id'),
    namespace = process.env.NAMESPACE || versionInfo.namespace || requireValue('namespace'),
    branch_slug = process.env.BRANCH_SLUG || versionInfo.BRANCH_SLUG || undefined,
    redirect_status_code = process.env.REDIRECT_STATUS_CODE || 302,
    path = requireValue('path'),
    version = process.env.VERSION || versionInfo.version || requireValue('version')
  } = options

  logger('BRANCH=' + branch)
  logger('BRANCH_SLUG=' + branch_slug)
  logger('BUILD_ID=' + build_id)
  logger('NAMESPACE=' + namespace)
  logger('VERSION=' + version)
  logger('REDIRECT_STATUS_CODE=' + redirect_status_code)


  let subOptions = {
    envs: [
      { name: 'ASSEMBLY_VERSION', value: assembly_version },
      { name: 'BRANCH_SLUG', value: branch_slug },
      { name: 'BRANCH', value: branch },
      { name: 'BUILD_ID', value: build_id },
      { name: 'NAMESPACE', value: namespace },
      { name: 'VERSION', value: version },
      { name: 'CWD', value: process.cwd() },
      { name: 'REDIRECT_STATUS_CODE', value: redirect_status_code },
    ],
    system: false,
    syntax: 'dollar-basic',
    all: true
  };

  logger(`Looking in ${path}`)

  var envPath = `${process.cwd()}/.env`;
  if (fs.existsSync(envPath))
    options.envFiles = [envPath];

  var stats = fs.statSync(path);

  const files = stats.isDirectory() ?
    flattenArray(findFiles(`${path}`)) :
    [path];

  await Promise.all(files.map(file => envsub({ templateFile: file, outputFile: file, options: subOptions })
    .then((result) => {
      let filePath = result.outputFile.replace(process.cwd(), '.')
      logger(`Replaced in: ${filePath}`)
    })
    .catch(err => {
      console.error(err.message);
    })))

}
