enum Level {
    debug = 'debug',
    info = 'info',
    error = 'error',
  }
  type Message = {
    level: Level;
    module: string;
    procedure: string;
    message: string;
    time: number;
  };
  
  export function ObjectPrint(obj: Record<string, any>) {
    let res = '';
    for (const key in obj) {
      const value = obj[key];
      res += `\n${key}:${JSON.stringify(value)}`
    }
    res += '\n'
    return res;
  }
  

export const Logger = {
    messages: [] as Message[],
    consoleOutput: true,
    printModule: [],
    info(module: string, procedure: string, message: string) {
      this._append(Level.info, module, procedure, message);
    },
    debug(module: string, procedure: string, message: string) {
      this._append(Level.debug, module, procedure, message);
    },
    error(module: string, procedure: string, message: string) {
      this._append(Level.error, module, procedure, message);
    },
    save(module: string, procedure: string, message: any) { },
    _append(level: Level, module: string, procedure: string, message: string) {
      let log = {
        level,
        module,
        procedure,
        message: String(message),
        time: new Date().getTime(),
      };
      this.messages.push(log);
      if (this.consoleOutput) {
        this._print(log);
      }
      if (this.messages.length > 15000) this.messages.shift();
    },
    _print(log: Message) {
      let time = new Date(log.time);
      console.info(
        '[' +
        (log.level == 'error' ? 'x' : '*') +
        '][' +
        time.toLocaleString() +
        '](' +
        log.module +
        ' - ' +
        log.procedure +
        ') ' +
        log.message
      );
    },
    filter(module: string, procedure: string) {
      return this.messages.filter((i) => i.module == module && i.procedure == procedure);
    },
    enableConsoleOutput() {
      this.consoleOutput = true;
      localStorage.setItem('Looger-consoleOutput', 'true')
    },
    disableConsoleOutput() {
      this.consoleOutput = false;
      localStorage.removeItem('Looger-consoleOutput')
    },
    setPrintModule(modules: string[]) {
      // this.printModule = modules;
      // localStorage.setItem('Looger-print-module', modules.join(' , '));
    },
    peek(rows: number) {
      return this.messages.slice(-rows);
    },
    search(module: string, procedure: string, keyword?: string) {
      return this.messages.filter((i: Message) => {
        let r = i.module == module;
        if (!r) return false;
        if (procedure) {
          if (i.procedure != procedure) return false;
        }
        if (keyword) {
          if (i.message.indexOf(keyword) == -1) return false;
        }
        return true;
      });
    },
  };