import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { CollectionService } from '../../../../core/services/collection.service'; import { Collection } from '../../../../shared/models/collection.model'; import { DatePipe } from '@angular/common'; import { CollectionEditModalComponent } from '../collection-edit-modal/collection-edit-modal.component'; import { MatDialog } from '@angular/material/dialog'; import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component'; import { ScreenshotService } from '../../../../core/services/screenshot.service'; import { CollectionEntryDTO } from '../../../../shared/models/dtos/collection-entry-dto.model'; import { environment } from '../../../../../environments/environment.prod'; @Component({ selector: 'app-collection-info-page', templateUrl: './collection-info-page.component.html', styleUrls: ['./collection-info-page.component.css'], providers: [DatePipe], }) export class CollectionInfoPageComponent implements OnInit { collection: Collection = {} as Collection; createdAt: string = ''; updatedAt: string = ''; viewMode: string = 'grid'; screenMode: boolean = false; constructor( private route: ActivatedRoute, private collectionService: CollectionService, private screenshotService: ScreenshotService, private datePipe: DatePipe, public dialog: MatDialog, private router: Router ) {} ngOnInit(): void { const id = this.route.snapshot.paramMap.get('id'); if (id == null) return; // todo redirect if no id is provided this.collection.id = parseInt(id); this.fetchCollection(); } fetchCollection() { this.collectionService.getCollection(this.collection.id).subscribe({ next: (result) => { this.collection = result; if (!this.collection.isUserCollection) this.collection.entries = this.sortEntries(this.collection.entries); this.createdAt = this.getCreatedDate()?.toString() || ''; this.updatedAt = this.getUpdatedAt()?.toString() || ''; // console.log( // `Collection "${this.collection.name}" received:`, // this.collection // ); }, error: (error) => { console.error('Error occurred:', error); }, }); } sortEntries(entries: CollectionEntryDTO[]) { return entries.sort( (a, b) => new Date(a.release_date).getTime() - new Date(b.release_date).getTime() ); } getListId() { return this.collection.id + ''; } getCreatedDate() { return this.datePipe.transform(this.collection.createdAt, 'dd MMMM, yyyy'); } // TODO use a relativeDate pipe getUpdatedAt() { const updatedAt = this.collection.updatedAt; // First, check if updatedAt is a valid date string or timestamp const modifiedDate = new Date(updatedAt); // Check if the date is invalid if (isNaN(modifiedDate.getTime())) { // console.error('Invalid date:', updatedAt); // Handle invalid date, perhaps return a fallback message or undefined return 'Date not available'; } const now = new Date(); const diffInMs = now.getTime() - modifiedDate.getTime(); const diffInDays = diffInMs / (1000 * 60 * 60 * 24); let isPlural = ''; if (diffInDays < 7) { // Less than a week, show relative time if (diffInDays < 1) { const diffInHours = diffInMs / (1000 * 60 * 60); if (diffInHours < 1) { const diffInMinutes = diffInMs / (1000 * 60); if (diffInMinutes >= 2) isPlural = 's'; return `${Math.floor(diffInMinutes)} minute${isPlural} ago`; } if (diffInHours >= 2) isPlural = 's'; return `${Math.floor(diffInHours)} hour${isPlural} ago`; } if (diffInDays >= 2) isPlural = 's'; return `${Math.floor(diffInDays)} day${isPlural} ago`; } else { // More than a week, show formatted date return this.datePipe.transform(modifiedDate, 'dd MMMM, yyyy'); } } openEditModal() { if (!this.collection) return; const dialogRef = this.dialog.open(CollectionEditModalComponent, { width: '50%', data: { name: this.collection.name, description: this.collection.description, userRating: this.collection.userRating || 0, poster: this.getCollectionPosterPath(this.collection), backdrop: this.getCollectionBackdropPath(this.collection), }, }); dialogRef.afterClosed().subscribe((result) => { if (result) { if (result.formData == null) return; this.collectionService .updateCollection(this.collection.id, result.formData) .subscribe({ next: (result) => { if (result) { // TODO TOAST collection update this.collection = result; } }, error: (error) => { console.error('Error updating collection:', error); // TODO error notification }, }); } }); } switchViewMode() { this.viewMode = this.viewMode == 'grid' ? 'table' : 'grid'; } deleteCollection() { if (!this.collection) return; const dialogRef = this.dialog.open(ConfirmModalComponent, { width: '400px', data: { title: 'Confirmation', message: 'Are you sure you want to delete this collection? This action cannot be undone and you will be unable to recover any data.', type: 'danger', }, }); dialogRef.afterClosed().subscribe((result) => { if (result) { if (result.confirmed != true) return; this.collectionService.deleteCollection(this.collection.id).subscribe({ next: () => { // TODO confirm notification this.router.navigate(['/collections']); }, error: (error) => { console.error('Error updating collection:', error); // TODO error notification }, }); } }); } shareScreenshot() { this.screenMode = true; const oldViewMode = this.viewMode; this.viewMode = 'grid'; this.screenshotService .capture('gridDiv') .then((dataUrl) => { this.copyToClipboard(dataUrl); }) .catch((error) => { console.error('Error capturing screenshot:', error); }); this.screenMode = false; this.viewMode = oldViewMode; } private copyToClipboard(dataUrl: string) { const img = new Image(); img.src = dataUrl; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); img.onload = () => { canvas.width = img.width; canvas.height = img.height; ctx!.drawImage(img, 0, 0); canvas.toBlob((blob) => { const item = new ClipboardItem({ 'image/png': blob as Blob }); navigator.clipboard.write([item]); }); }; } refreshCollection() { this.collectionService.refreshCollection(this.collection.id).subscribe({ next: (data) => { this.collection = data as unknown as Collection; this.collection.entries = this.collection .entries as CollectionEntryDTO[]; this.createdAt = this.getCreatedDate()?.toString() || ''; this.updatedAt = this.getUpdatedAt()?.toString() || ''; // console.log( // `Collection "${this.collection.name}" received:`, // this.collection // ); }, error: (error) => { console.error('Error occurred:', error); }, }); } getCollectionParts() { this.collectionService.getCollectionParts(this.collection.id).subscribe({ next: (data) => { this.collection = data as unknown as Collection; this.collection.entries = this.collection .entries as CollectionEntryDTO[]; this.createdAt = this.getCreatedDate()?.toString() || ''; this.updatedAt = this.getUpdatedAt()?.toString() || ''; // console.log( // `Collection "${this.collection.name}" received:`, // this.collection // ); }, error: (error) => { console.error('Error occurred:', error); }, }); } redirectToTMDB() { window.open( `https://www.themoviedb.org/collection/${this.collection.tmdbId}`, '_blank' ); } getCollectionPosterPath(collection: Collection) { // console.log(`collection media:`, collection.medias); if (collection.medias && collection.medias.length != 0) { const posters = collection.medias.filter((m) => m.type == 'poster'); if (posters.length != 0) { const selectedPosters = posters.filter((m) => m.isSelected); // console.log(selectedPosters); let selectedPoster; if (selectedPosters.length != 0) { selectedPoster = selectedPosters[0].path; } else { selectedPoster = posters[0].path; } return ( environment.API_URL + `/media/collections/posters/preview/${selectedPoster}` ); } } // if (collection.entries && collection.entries.length != 0) { // // * use the poster of the first entry in the collection // // * if the collection is empty // return this.getEntryBackdropPath(collection.entries[0]); // } else if (collection.posterPath) { // * use first remote tmdb poster // * if collection has none and has no entry return `https://image.tmdb.org/t/p/w1280/${collection.posterPath}`; } else { // * use default poster // * if collection has totaly no poster return 'assets/images/default/default-poster.png'; } } getCollectionBackdropPath(collection: Collection) { // console.log(`collection media:`, collection.medias); if (collection.medias && collection.medias.length != 0) { const backdrops = collection.medias.filter((m) => m.type == 'backdrop'); if (backdrops.length != 0) { const selectedBackdrops = backdrops.filter((m) => m.isSelected); // console.log(selectedBackdrops); let selectedBackdrop; if (selectedBackdrops.length != 0) { selectedBackdrop = selectedBackdrops[0].path; } else { selectedBackdrop = backdrops[0].path; } return ( environment.API_URL + `/media/collections/backdrops/preview/${selectedBackdrop}` ); } } // if (collection.entries && collection.entries.length != 0) { // // * use the poster of the first entry in the collection // // * if the collection is empty // return this.getEntryBackdropPath(collection.entries[0]); // } else if (collection.backdropPath) { // * use first remote tmdb poster // * if collection has none and has no entry return `https://image.tmdb.org/t/p/w1280/${collection.backdropPath}`; } else { // * use default poster // * if collection has totaly no poster return 'assets/images/default/default-backdrop.png'; } } onRefrechEvent(eventData: any) { if (eventData.type == 'delete') { this.collection.entries = this.collection.entries.filter( (e) => e.id != eventData.id ); } } }