import { Directive, HostListener, inject, Input } from '@angular/core'
import { DialogService, ErrorService, i18nKey } from '@start9labs/shared'
import { TuiNotificationMiddleService } from '@taiga-ui/kit'
import { PolymorpheusComponent } from '@taiga-ui/polymorpheus'
import { filter } from 'rxjs'
import { ApiService } from 'src/app/services/api/embassy-api.service'
import { SnakeComponent } from './snake.component'

@Directive({
  selector: 'img[snake]',
})
export class SnakeDirective {
  private readonly loader = inject(TuiNotificationMiddleService)
  private readonly errorService = inject(ErrorService)
  private readonly api = inject(ApiService)
  private readonly dialog = inject(DialogService)

  @Input()
  snake = 0

  @HostListener('click')
  async onClick() {
    this.dialog
      .openComponent<number>(new PolymorpheusComponent(SnakeComponent), {
        label: 'Snake!' as i18nKey,
        size: 'l',
        closable: false,
        dismissible: false,
        data: this.snake,
      })
      .pipe(filter(score => score > this.snake))
      .subscribe(async score => {
        const loader = this.loader.open('Saving high score').subscribe()

        try {
          await this.api.setDbValue<number>(['snakeHighScore'], score)
        } catch (e: any) {
          this.errorService.handleError(e)
        } finally {
          loader.unsubscribe()
        }
      })
  }
}
