/*
  Really simple logging system in browsers that just makes the usual
  `console.log` bindings available in a `log` variable.  That makes
  the code similar to in the Node.js code such as in `api/`.  It also
  lets you remove levels as in the `logger()`.
 */
import { log_levels } from "./config.js";
const disabled = () => {};

/*
  We have to do this because rendered pages will include
  client components but they don't have a window variable.
  We try to use window to bind, and if it doesn't work then
  just use the base function.  One question? Why bind window?
 */
const bind_logging = () => {
  try {
    return {
      debug: console.log.bind(window.console),
      warn: console.warn.bind(window.console),
      info: console.info.bind(window.console),
      error: console.error.bind(window.console),
      table: console.table.bind(window.console),
      assert: console.assert.bind(window.console),
    }
  } catch(error) {
    return {
      debug: console.log,
      warn: console.warn,
      info: console.info,
      error: console.error,
      table: console.table,
      assert: console.assert
    }
  }
}

const all_levels = bind_logging();

const as_entries = Object.entries(all_levels);

/*
  The main way you create a logger for your code.  This will remove
  a log level, but it's replaced by this function:

  ```javascript
  const disabled = () => {};
  ```

  ___BUG___: I'm not sure if modern compilers will remove this function or not.  It
  does remove the log message from the output, so if you want to hide debugging infor
  spamming the console then that works.

  + `levels Array[string]` -- A list of log levels to display.
  */
export const logger = (levels = log_levels) => {
  return Object.fromEntries(as_entries.map(([level, logf]) => {
    return levels.includes(level) ? [level, logf] : [level, disabled];
  }));
}

/*
  A default logger you can use when you don't care what's being logged
  or just want to use the `log_levels` configuration from `client/config.js`.
 */
export const log = logger();
