import { Directive, inject, Output } from '@angular/core'
import { WaIntersectionObserveeService } from '@ng-web-apis/intersection-observer'
import { convertAnsi, ErrorService } from '@start9labs/shared'
import { catchError, defer, filter, from, map, of, switchMap, tap } from 'rxjs'
import { LogsComponent } from './logs.component'

@Directive({
  selector: '[logsFetch]',
})
export class LogsFetchDirective {
  private readonly observer = inject(WaIntersectionObserveeService)
  private readonly component = inject(LogsComponent)
  private readonly errors = inject(ErrorService)

  @Output()
  readonly logsFetch = defer(() => this.observer).pipe(
    filter(([entry]) => !!entry?.isIntersecting && !this.component.scroll),
    switchMap(() =>
      from(
        this.component.fetchLogs({
          cursor: this.component.startCursor ?? undefined,
          before: true,
          limit: 400,
        }),
      ),
    ),
    tap(res => {
      if (res.startCursor) {
        this.component.setCursor(res.startCursor)
      }
    }),
    map(({ entries }) => convertAnsi(entries)),
    catchError(e => {
      this.errors.handleError(e)

      return of('')
    }),
  )
}
