import { stub } from 'eltro'
import lowdb from '../core/db.mjs'
import Util from '../core/util.mjs'

export function createFakeLog() {
  return {
    debug: stub(),
    info: stub(),
    warn: stub(),
    error: stub(),
    fatal: stub(),
    event: {
      info: stub(),
      warn: stub(),
      error: stub(),
    }
  }
}

export function createFakeContext(config = { }, util = new Util(import.meta.url), filename = null) {
  const log = createFakeLog()

  return lowdb(config, log, filename).then(function(res) {
    return {
      db: res,
      util: util,
      log: log,
      core: { },
    }
  })
}

var colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

let levels = {
  10: 'TRACE',
  20: 'DEBUG',
  30: 'INFO',
  40: 'WARN',
  50: 'ERROR',
  60: 'FATAL',
}
var levelcolor = {
  10: 'white',    // TRACE
  20: 'yellow',   // DEBUG
  30: 'cyan',     // INFO
  40: 'magenta',  // WARN
  50: 'red',      // ERROR
  60: 'inverse',  // FATAL
};

function style(str, color) {
  if (!str)
    return '';
  var codes = colors[color];
  if (codes) {
    return '\x1B[' + codes[0] + 'm' + str +
           '\x1B[' + codes[1] + 'm';
  } else {
    return str;
  }
}

export function prettyPrintMessage(line) {
  if (line[0] === '{') {
    try {
      let rec = JSON.parse(line)
      console.log(`[${rec.time.substr(11).replace('Z', '')}] ${style(levels[rec.level], levelcolor[rec.level])}: ${rec.name} ${style('(pid: ' + rec.pid + ')', 'grey')}: ${style(rec.msg, 'cyan')}`)
      if (rec.err && rec.err.message && rec.err.stack) {
        let err = new Error(rec.err.message)
        err.stack = rec.err.stack
        console.log(err)
      }
      return
    } catch { }
  }
  console.log(line)
}
