import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Pin } from '../../model/Pin';
import { ImageService } from '../../services/image/image.service';
import { PinService } from '../../services/pin/pin.service';

@Component({
  selector: 'app-timeline',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './timeline.component.html',
})
export class TimelineComponent implements OnInit {
  pins: Pin[] = [];
  imageUrls: SafeUrl[][] = [];
  loading = true;

  constructor(
    private pinService: PinService,
    private imageService: ImageService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit(): void {
    this.pinService.getPins().subscribe((pins: Pin[]) => {
      this.pins = pins
        .filter((pin) => !!pin.date)
        .sort((a, b) => (a.date! > b.date! ? 1 : -1));
      this.imageUrls = this.pins.map(() => []); // initialise le tableau d'images

      this.pins.forEach((pin, index) => {
        if (pin.files && pin.files.length > 0) {
          pin.files.forEach((imageId) => {
            this.imageService.getImage(imageId).subscribe((blob) => {
              const objectUrl = URL.createObjectURL(blob);
              const safeUrl = this.sanitizer.bypassSecurityTrustUrl(objectUrl);
              this.imageUrls[index].push(safeUrl);
            });
          });
        }
      });

      this.loading = false;
    });
  }
}
