import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {TableModule} from 'primeng/table';
import {AuthService} from '../../auth.service';
import {AuthorService} from '../../services/author.service';
import {Author} from '../../models/author';
import {Subscription} from 'rxjs';
import {MessageService} from 'primeng/api';
import {AvatarModule} from 'primeng/avatar';
import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';
import {RegisterFormComponent} from '../../components/register-form/register-form.component';

@Component({
  selector: 'app-admin-authors',
  standalone: true,
  imports: [
    HeaderComponent,
    TableModule,
    AvatarModule,
    Button,
    DialogModule,
    RegisterFormComponent,
  ],
  templateUrl: './admin-authors.component.html',
  styleUrl: './admin-authors.component.css'
})
export class AdminAuthorsComponent implements OnDestroy{
  authors: Author[] = [];
  createAuthorDialogVisibility: boolean = false;
  updateDialogVisibility: boolean[] = [];
  deleteDialogVisibility: boolean[] = [];
  subs: Subscription[] = [];

  constructor(private authService: AuthService,
              private authorService: AuthorService,
              private messageService: MessageService) {
    this.authorService.list().subscribe({
      next: (authors: Author[]) => {
        this.authors = authors;
      },
      error: (error) => {
        this.failureMessage("Erreur", error.error.message)
      }
    })
  }

  closeCreateAuthorDialog(author: Author): void {
    this.authors.push(author);
    this.createAuthorDialogVisibility = false;
  }

  successMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'success',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  deleteAuthor(authorId: string, rowIndex: number): void {
  }

  openDialog(dialogBooleanTab: boolean[], index: number) {
    dialogBooleanTab[index] = true;
  }

  closeDialog(dialogBooleanTab: boolean[], index: number) {
    dialogBooleanTab[index] = false;
  }

  failureMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'error',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  ngOnDestroy(): void {
    this.subs.forEach(sub => sub.unsubscribe());
  }
}
