export {}

type ConsoleMessages = {
  time: string
  messages: Array<any>
  type: MessageType
}

type MessageType = 'info' | 'warn' | 'debug' | 'error'

export const logger = () => {
  let _messages: Array<ConsoleMessages> = []
  const originalConsole = window.console

  const log = (message?: any, ...optionalParams: any[]) => {
    originalConsole.log.apply(originalConsole, [message, ...optionalParams])
    appendLog('info', message, optionalParams)
  }
  const info = (message?: any, ...optionalParams: any[]) => {
    originalConsole.info.apply(originalConsole, [message, ...optionalParams])
    appendLog('info', message, optionalParams)
  }
  const error = (message?: any, ...optionalParams: any[]) => {
    originalConsole.error.apply(originalConsole, [message, ...optionalParams])
    appendLog('error', message, optionalParams)
  }

  const warn = (message?: any, ...optionalParams: any[]) => {
    originalConsole.warn.apply(originalConsole, [message, ...optionalParams])
    appendLog('warn', message, optionalParams)
  }

  const debug = (message?: any, ...optionalParams: any[]) => {
    originalConsole.debug.apply(originalConsole, [message, ...optionalParams])
    appendLog('debug', message, optionalParams)
  }

  const dump = () => {
    return JSON.stringify(_messages, null, 4)
  }

  const appendLog = (method: string, message: any, ...optionalParams: any[]) => {
    _messages.push({
      time: new Date().toLocaleString('sv', { timeZoneName: 'short' }),
      type: method,
      messages: [message, ...optionalParams],
    } as ConsoleMessages)
  }

  const clear = () => {
    _messages = []
  }

  return {
    log,
    info,
    error,
    warn,
    debug,
    dump,
    clear,
  }
}
