import boxen from 'boxen'
import chalk from 'chalk'

const { max } = Math

let log

export default function serverlessLog(msg) {
  if (log) {
    log(msg, 'offline')
  }
}

export function setLog(serverlessLogRef) {
  log = serverlessLogRef
}

// logs based on:
// https://github.com/serverless/serverless/blob/master/lib/classes/CLI.js

function logRoute(httpMethod, server, stage, path, maxLength) {
  return `${chalk.keyword('dodgerblue')(
    `${httpMethod.padEnd(maxLength, ' ')} |`,
  )} ${chalk.keyword('grey').dim(`${server}/${stage}`)}${chalk.keyword('lime')(
    path,
  )}`
}

function getMaxHttpMethodNameLength(routeInfo) {
  return max(...routeInfo.map(({ method }) => method.length))
}

export function logRoutes(routeInfo) {
  const maxLength = getMaxHttpMethodNameLength(routeInfo)
  const boxenOptions = {
    borderColor: 'yellow',
    dimBorder: true,
    margin: 1,
    padding: 1,
  }

  console.log(
    boxen(
      routeInfo
        .map(({ method, path, server, stage }) =>
          logRoute(method, server, stage, path, maxLength),
        )
        .join('\n'),
      boxenOptions,
    ),
  )
}

export function logWarning(msg) {
  console.log(`offline: ${chalk.keyword('red')(msg)}`)
}

@@ -68,16 +68,161 @@
 = Math%0A%0A
+const blue = chalk.keyword('dodgerblue')%0Aconst grey = chalk.keyword('grey')%0Aconst lime = chalk.keyword('lime')%0Aconst red = chalk.keyword('red')%0A%0A
 let log%0A
@@ -556,41 +556,13 @@
  %60$%7B
-chalk.keyword('dodgerblue')(%0A    
+blue(
 %60$%7Bh
@@ -601,43 +601,27 @@
 %7D %7C%60
-,%0A  
 )%7D $%7B
-chalk.keyword('
 grey
-')
 .dim(
+%0A    
 %60$%7Bs
@@ -640,47 +640,25 @@
 ge%7D%60
-)%7D$%7Bchalk.keyword('lime')(%0A    path,%0A  
+,%0A  )%7D$%7Blime(path
 )%7D%60%0A
@@ -1257,36 +1257,19 @@
 line: $%7B
-chalk.keyword('
 red
-')
 (msg)%7D%60)

Simplify cli colorization