import { Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { MediaFileComponent } from '../media-file/media-file.component';
import { MediaFileService } from '../media-files/media-file.service';
import { MediaFile } from '../media-files/media-file.model';

@Component({
  selector: 'app-media-files-list',
  imports: [MediaFileComponent],
  templateUrl: './media-files-list.component.html',
  styleUrl: './media-files-list.component.css'
})
export class MediaFilesListComponent implements OnInit {
  files = signal<MediaFile[]>([]);
  isFetching = signal(false);
  error = signal('');
  private mediaFileService = inject(MediaFileService);
  private destroyRef = inject(DestroyRef);

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

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