import { Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { Artist } from '../comic.model';
import { ComicArtistComponent } from '../comic-artist/comic-artist.component';
import { ArtistService } from '../comic-artists/artist.service';

@Component({
  selector: 'app-comic-artists-list',
  imports: [ComicArtistComponent],
  templateUrl: './comic-artists-list.component.html',
  styleUrl: './comic-artists-list.component.css'
})
export class ComicArtistsListComponent implements OnInit {
  
  artists = signal<Artist[]>([]);
  isFetching = signal(false);
  error = signal('');
  private artistService = inject(ArtistService);
  private destroyRef = inject(DestroyRef);

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

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