import { Injectable } from '@angular/core';
import { UserStateService } from '@swagger/isa';
import { Log } from '@swagger/isa';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class LoggingService {
  constructor(private userStateService: UserStateService) {}

  log(message: string, error: any, logType: LogType) {
    console.error(message, error);
    if (error instanceof Error) {
      this.logError(message, error, logType);
    } else if (error instanceof HttpErrorResponse) {
      this.logHttpError(message, error, logType);
    } else {
      this.logOtherError(message, error, logType);
    }
  }

  private logError(message: string, error: Error, logType: LogType) {
    const log = <Log>{
      message: message,
      content: `Name: ${error.name} , Message: ${error.message}, Stack: ${error.stack}`,
      logType: logType,
    };
    this.userStateService
      .UserStateSaveLog(log)
      .toPromise()
      .catch((err) => console.error('Logging failed: ', err));
  }

  private logHttpError(message: string, error: HttpErrorResponse, logType: LogType) {
    const log = <Log>{
      message: message,
      content: `Name: ${error.name}, Url: ${error.url} Status: ${error.status} , Message: ${error.message}`,
      logType: logType,
    };
    this.userStateService
      .UserStateSaveLog(log)
      .toPromise()
      .catch((err) => console.error('Logging failed: ', err));
  }

  private logOtherError(message: string, error: any, logType: LogType) {
    const log = <Log>{
      message: message,
      content: error.message,
      logType: logType,
    };
    this.userStateService
      .UserStateSaveLog(log)
      .toPromise()
      .catch((err) => console.error('Logging failed: ', err));
  }
}

export enum LogType {
  Trace,
  Debug,
  Information,
  Warning,
  Error,
  Critical,
  None,
}
