import { Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { Publisher } from '../comic.model';
import { PublisherService } from '../comic-publishers/publisher.service';
import { ComicPublisherComponent } from "../comic-publisher/comic-publisher.component";

@Component({
  selector: 'app-comic-publishers-list',
  imports: [ComicPublisherComponent],
  templateUrl: './comic-publishers-list.component.html',
  styleUrl: './comic-publishers-list.component.css'
})
export class ComicPublishersListComponent implements OnInit {
  publishers = signal<Publisher[]>([]);
  isFetching = signal(false);
  error = signal('');
  private publisherService = inject(PublisherService);
  private destroyRef = inject(DestroyRef);

  ngOnInit() {
    this.isFetching.set(true);
    const subscription = this.publisherService.loadPublishers().subscribe({
      next: (publishers) => {
        this.publishers.set(publishers);
      },
      error: (error: Error) => {
        this.error.set(error.message);
      },
      complete: () => {
        this.isFetching.set(false);
      },
    });

    this.destroyRef.onDestroy(() => {
      subscription.unsubscribe();
    });
  }
}
