import { Injectable, Injector } from '@angular/core'
import { SASjsConfig } from '@sasjs/adapter'
import { SasService } from './sas.service'

@Injectable({
  providedIn: 'root'
})
export class LoggerService {
  private sasjsConfig: SASjsConfig | undefined

  constructor(private injector: Injector) {}

  public log(message: any, optionalParameters?: any) {
    this.injectSasService()

    if (this.sasjsConfig?.debug)
      optionalParameters
        ? console.log(message, optionalParameters)
        : console.log(message)
  }

  public error(message: any, optionalParameters?: any) {
    console.error(message, optionalParameters)
  }

  public logRequestData(program: string, data: { [key: string]: any }) {
    this.log('--- Adapter Request Input ---')
    this.log(program)

    if (!data) {
      this.log('no data sent')
      return
    }

    for (let key of Object.keys(data)) {
      this.log(key, data[key])
    }

    this.log('------')
  }

  private injectSasService() {
    if (!this.sasjsConfig) {
      const sasService = this.injector.get(SasService)
      this.sasjsConfig = sasService.getSasjsConfig()
    }
  }
}
