// const path = require('path')
const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const shell = require('shelljs')
const handlebars = require('handlebars')

const { log } = require('./utils/log')

const { TEMPLATES, PACKAGES, LEGACY_CODES } = require('./configs')

handlebars.registerHelper('if_eq', function(a, b, opts) {
  return a === b ? opts.fn(this) : opts.inverse(this)
})

const restoreLegacyCodes = () => {
  log.title('📤  Restore previous codes')
  LEGACY_CODES.regulars.forEach(file => {
    log.item(`Restoring ${file} ...`)
    const basename = path.basename(file)
    fs.copyFileSync(`${__dirname}/codes/old/${basename}`, file)
  })
  LEGACY_CODES.exceptions.forEach(file => {
    log.item(`Restoring ${file} ...`)
    const basename = path.basename(file)
    fs.copyFileSync(`${__dirname}/codes/old/exceptions/${basename}`, file)
  })
}

const updateConfigs = (mode = 'chill') => {
  TEMPLATES.forEach(file => {
    log.item(`Updating ${file} ...`)
    const content = fs.readFileSync(
      `${__dirname}/templates/${file}.template`,
      'utf8'
    )
    const template = handlebars.compile(content)
    const output = template({ mode })
    fs.writeFileSync(file, output, 'utf8')
  })
}

const restoreConfigs = () => {
  log.title('📤  Restore previous codes')
  TEMPLATES.forEach(file => {
    log.item(`Restoring ${file} ...`)
    const basename = path.basename(file)
    fs.copyFileSync(`${__dirname}/templates/${basename}`, file)
  })
}

const updateCodes = () => {
  LEGACY_CODES.regulars.forEach(file => {
    const basename = path.basename(file)
    log.item(`Updating ${basename} ...`)
    fs.copyFileSync(`${__dirname}/codes/new/${basename}`, file)
  })
  LEGACY_CODES.exceptions.forEach(file => {
    const basename = path.basename(file)
    log.item(`Updating ${basename} ...`)
    fs.copyFileSync(`${__dirname}/codes/new/exceptions/${basename}`, file)
  })
}

const updatePackages = () => {
  const command =
    'yarn add -D ' +
    PACKAGES.map(({ name, version }) => {
      log.item(`${name}:⛳️  ${chalk.bgGreen.black(version)}`)
      return `${name}@${version}`
    }).join(' ')
  const { code, stderr } = shell.exec(command)
  if (!code) console.error(stderr)
}

module.exports = {
  restoreLegacyCodes,
  updateConfigs,
  updateCodes,
  updatePackages,
  restoreConfigs
}
