/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { LoggerService, LogLevel, LogObject } from '@bci-web-core/core';
import { tap } from 'rxjs/operators';

@Component({
  selector: 'bci-logger-table',
  templateUrl: './logger-table.component.html',
  styleUrls: ['./logger-table.component.scss'],
})
export class LoggerTableComponent implements OnInit, AfterViewInit {
  displayedColumns = ['timestamp', 'loglevel', 'message'];
  data: LogObject[] = [];
  dataSource = new MatTableDataSource<LogObject>(this.data);

  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private logger: LoggerService) {}

  ngOnInit() {
    this.logger.messages$
      .pipe(
        tap((logObject) => (this.data = [logObject, ...this.data])),
        tap(() => (this.dataSource.data = this.data))
      )
      .subscribe();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  logInfo() {
    this.logger.info('This is an info log');
  }

  logDebug() {
    this.logger.debug('This is a debug log');
  }

  logError() {
    this.logger.error('This is an error', new Error('this is the error'));
  }

  getLogLevel(): string {
    return LogLevel[this.logger.logLevel];
  }
}
