const chalk = require('chalk')
const figlet = require('figlet')
const semver = require('semver')
const krnos = require('@krnos/kronos')

const { clearConsole } = require('@vue/cli-shared-utils')

exports.generateTitle = async function (checkUpdate) {
  const local = require('../../package.json').version
  const { current, latest } = await krnos.getVersions(local)

  let title = chalk.bold.blue(`Vue CLI v${current}`)

  title = chalk.cyan(
    figlet.textSync(`Controlla CLI v${current}`, { horizontalLayout: 'full' })
  )

  title += ' By Iván Sotelo'

  if (process.env.VUE_CLI_TEST) {
    title += ' ' + chalk.blue.bold('TEST')
  }
  if (process.env.VUE_CLI_DEBUG) {
    title += ' ' + chalk.magenta.bold('DEBUG')
  }
  if (checkUpdate && semver.gt(latest, current)) {
    if (process.env.VUE_CLI_API_MODE) {
      title += chalk.green(` 🌟️ Update available: ${latest}`)
    } else {
      title += chalk.green(`
┌───────────────────────${`─`.repeat(latest.length)}──┐
│  🌟️ Update available: ${latest}  │
└───────────────────────${`─`.repeat(latest.length)}──┘`)
    }
  }

  return title
}

exports.clearConsole = async function clearConsoleWithTitle (checkUpdate) {
  const title = await exports.generateTitle(checkUpdate)
  clearConsole(title)
}
