import fs from "fs"
import colors, { Color } from "colors"
import { NextApiRequest } from "next"
import { IncomingMessage } from "http"
colors.enable()

const loggingTemplates: { [key: string]: LoggingType } = {
  system: ["SYSTEM", "green"],
  "info.green": ["INFO", "green"],
  "info.cyan": ["INFO", "cyan"],
  debug: ["Debug", "grey"],
  post: ["Post", "white"],
  warn: ["WARN", "yellow"],
  error: ["ERROR", "red"],
}

type LoggingType = [string, keyof Color]
export type Logging = keyof typeof loggingTemplates | LoggingType

let started: boolean = false

async function logStartup() {
  await fs.promises.stat("log").catch(async () => {
    await fs.promises.mkdir("log")
    await logging(`Created 'log' Folder.`, ["info.cyan", "system"])
  })
  started = true
}

async function logging(
  message: string,
  types: Logging[],
  req?: NextApiRequest | IncomingMessage
) {
  if (!started) await logStartup()
  const messages = { console: message, file: message }
  types
    .slice()
    .reverse()
    .forEach(async (type) => {
      const [name, color] =
        typeof type === "object" ? type : loggingTemplates[type]
      messages.console = `[${name}] `[color] + messages.console
      messages.file = `[${name}] ` + messages.file
    })
  messages.console =
    `[${new Date().toString().slice(0, 33)}] ` + messages.console
  messages.file = `[${new Date().toString().slice(0, 33)}] ` + messages.file
  if (req) {
    const forwardedFor: any = req.headers["x-forwarded-for"]
    const ip = (forwardedFor || "127.0.0.1, 192.168.178.1").split(",")
    messages.console = ip[0].yellow + " - " + messages.console
    messages.file = ip[0] + " - " + messages.file
  }
  await fs.promises.appendFile("log/log.txt", messages.file + "\n")
  console.log(messages.console)
}

export default logging
