// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import { type LevelName, LogLevels } from "./levels.ts";
import type { LogRecord } from "./logger.ts";
import { blue, bold, red, yellow } from "jsr:@std/fmt@^1.0.2/colors";
import { BaseHandler, type BaseHandlerOptions } from "./base_handler.ts";

export interface ConsoleHandlerOptions extends BaseHandlerOptions {
  useColors?: boolean;
}

/**
 * This is the default logger. It will output color coded log messages to the
 * console via `console.log()`.
 */
export class ConsoleHandler extends BaseHandler {
  #useColors?: boolean;

  constructor(levelName: LevelName, options: ConsoleHandlerOptions = {}) {
    super(levelName, options);
    this.#useColors = options.useColors ?? true;
  }

  override format(logRecord: LogRecord): string {
    let msg = super.format(logRecord);

    if (this.#useColors) {
      msg = this.applyColors(msg, logRecord.level);
    }

    return msg;
  }

  applyColors(msg: string, level: number): string {
    switch (level) {
      case LogLevels.INFO:
        msg = blue(msg);
        break;
      case LogLevels.WARN:
        msg = yellow(msg);
        break;
      case LogLevels.ERROR:
        msg = red(msg);
        break;
      case LogLevels.CRITICAL:
        msg = bold(red(msg));
        break;
      default:
        break;
    }

    return msg;
  }

  log(msg: string) {
    console.log(msg);
  }
}

// denoCacheMetadata={"headers":{"etag":"\"f2a40864e8f42a897ddd07381ad416e5\"","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=lwQVMrJce3LA2qNlr8aZZfvfrak%2BTOwM0bAfOxyBhl2kf4NxjC0%2F%2BlvMgi8dJSRL5FHqc3UrvNE5FrIoZ9BXQvvbd4JZaGFeUEEpuphtbmAJM2A8cCndB%2Bk%3D\"}]}","content-type":"text/typescript","vary":"Origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","cache-control":"public, max-age=31536000, immutable","access-control-expose-headers":"*","x-jsr-backend":"modules","set-cookie":"__cf_bm=6PNUzTqtTrKuFfZrL6u6wIGfFsupdEf6NYQMo_ZfMH0-1785241875.0921762-1.0.1.1-__iBXZJO_jnXEz8yIr.MEHu_hOe8LPKNKJ7QVXLdvf8Syin1MHOPPezNA8nHSDQaaltTpCFDVdw.JXn5kH06QIuJTmIfv2jetPkZNyHEAMqPhi74bAFAoTwKzxwC3kNz; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","x-robots-tag":"noindex","server":"cloudflare","x-content-type-options":"nosniff","cf-ray":"a223e65759607db6-LAX","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","alt-svc":"h3=\":443\"; ma=86400","content-length":"1464","access-control-allow-origin":"*"},"url":"https://jsr.io/@std/log/0.224.7/console_handler.ts","time":1785241875}