Files
Showy/frontend/src/app/features/entry/entry-page/entry-page.component.ts
T

524 lines
15 KiB
TypeScript

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { trigger, style, transition, animate } from '@angular/animations';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { Entry } from '../../../shared/models/entry.model';
import { EpisodeSeenDto } from '../../../shared/models/dtos/episode-seen.dto';
import { UserCollectionsModalComponent } from '../../../shared/components/modals/list-selection-modal/user-collections-modal.component';
import { SeenModalComponent } from '../../../shared/components/modals/seen-modal/seen-modal.component';
import { ConfirmModalComponent } from '../../../shared/components/modals/confirm-modal/confirm-modal.component';
import { EntrySeenService } from '../../../core/services/entry-seen.service';
import { EntryRatingsService } from '../../../core/services/entry-ratings.service';
import { EntryService } from '../../../core/services/entry.service';
import { EpisodeSeenService } from '../../../core/services/episode-seen.service';
import { SeasonService } from '../../../core/services/season.service';
import { LibraryService } from '../../../core/services/library.service';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-entry-page',
templateUrl: './entry-page.component.html',
styleUrls: ['./entry-page.component.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('fadeInOut', [
transition(':enter', [
// void => *
style({ opacity: 0 }),
animate('0.5s ease-in', style({ opacity: 1 })),
]),
transition(':leave', [
// * => void
animate('0.5s ease-out', style({ opacity: 0 })),
]),
]),
],
})
export class EntryPageComponent implements OnInit {
entry: Entry = {} as Entry;
public showAll = false;
public initialCount = 2;
lockActions: boolean = false;
seenHistory: any[] = [];
seenHistoryToShow: any[] = [];
itemsCount: number = 0;
maxPage: number = 10;
currentPage: number = 1;
pageSize: number = 10;
constructor(
private episodeSeenService: EpisodeSeenService,
private entryService: EntryService,
private seasonService: SeasonService,
private entrySeenService: EntrySeenService,
private entryRatingsService: EntryRatingsService,
private libraryService: LibraryService,
private dialog: MatDialog,
private route: ActivatedRoute,
private router: Router,
private toastr: ToastrService
) {}
ngOnInit(): void {
this.route.data.subscribe(
(data) => {
this.entry = data['entry'] as Entry;
if (this.entry.is_tvseries) {
// ? sorting seasons
this.entry.seasons = this.entry.seasons.sort((a, b) => {
if (b.season_number == 0) b.season_number = 30; // this will make the special season go last
if (a.season_number == 0) a.season_number = 30; // this will make the special season go last
return a.season_number - b.season_number;
});
// ? getting seaons episodes
this.entry.seasons.forEach((season) => {
this.seasonService.getSeasonEpisodes(season.id).subscribe({
next: (episodes) => {
// console.log(
// `Loaded Season ${season.season_number} Episodes (${episodes.length})`
// );
season.episodes = episodes;
},
error: (error) => {
console.log(`Couldn't fetch season episodes data:`, error);
this.toastr.success(
'Error',
`Couldn't get season ${season.season_number} episodes.`,
{
tapToDismiss: true,
progressBar: true,
progressAnimation: 'increasing',
}
);
season.episodes = [];
},
});
});
}
if (!this.entry) {
this.router.navigate(['/error'], {
queryParams: { error: 'Entry not found' },
});
}
},
(error) => {
console.error('Error when trying to access route data', error);
this.router.navigate(['/error'], {
queryParams: { error: 'Error fetching data' },
});
}
);
this.getEpisodesSeenHistory();
}
openEntrySeenModal() {
if (!this.entry) return;
const dialogRef = this.dialog.open(SeenModalComponent, {
width: '360px',
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
// console.log('Seen dialog closed with:', result);
if (result.watchDate == '') {
// TODO show no was passed date notification
return;
}
let watchDate = result.watchDate;
let watchedWith = result.watchedWith.split('\n').join(', ');
this.entrySeenService
.createEntrySeen(this.entry.id.toString(), watchDate, watchedWith)
.subscribe({
next: (entrySeen) => {
if (entrySeen) {
// TODO show confirm notification
// console.log(`EntrySeen Added`, entrySeen);
this.entry.entrySeen.push(entrySeen);
if (this.entry.watchlist) {
this.libraryService.refrechEntries().subscribe();
}
}
},
error: (error) => {
console.error('Error adding entrySeen:', error);
},
});
// TODO show notification
} else {
console.log('Seen dialog was cancelled');
}
});
}
onRatingChange(event: Event) {
this.entryRatingsService
.updateEntryRatings(this.entry.entryRating)
.subscribe({
next: (entryRatings) => {
if (entryRatings) {
// TODO show notification
this.entry.entryRating = entryRatings;
}
},
error: (error) => {
// TODO show notification
console.error('Error updating entryRatings:', error);
},
});
}
removeEntrySeen(id: number) {
const dialogRef = this.dialog.open(ConfirmModalComponent, {
width: '400px',
data: {
title: 'Confirmation',
message: `Are you sure you want to delete this?`,
type: 'danger',
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
if (result.confirmed != true) return;
this.entrySeenService.removeEntrySeen(id).subscribe({
next: () => {
this.toastr.success('success', `Removed successfuly.`, {
tapToDismiss: true,
progressBar: true,
progressAnimation: 'increasing',
});
this.entry.entrySeen = this.entry.entrySeen.filter(
(item) => item.id !== id
);
},
error: (error) => {
// TODO show notification
console.error('Error deleting entrySeen:', error);
},
});
}
});
}
toggleFavorite() {
this.lockActions = true;
this.entry.favorit = !this.entry.favorit;
this.entryService.updateEntry(this.entry).subscribe({
next: (entry) => {
// console.log(`Entry updated: `, entry);
this.entry = entry;
},
error: (error) => {
console.log(`Error updating entry: `, error);
this.entry.favorit = !this.entry.favorit;
},
complete: () => {
this.lockActions = false;
},
});
}
toggleHidden() {
this.lockActions = true;
this.entry.hidden = !this.entry.hidden;
this.entryService.updateEntry(this.entry).subscribe({
next: (entry) => {
// console.log(`Entry updated: `, entry);
this.entry = entry;
},
error: (error) => {
console.log(`Error updating entry: `, error);
this.entry.favorit = !this.entry.favorit;
},
complete: () => {
this.lockActions = false;
}
});
}
showAddToListModal() {
if (this.entry) {
const dialogRef = this.dialog.open(UserCollectionsModalComponent, {
width: '400px',
height: '55%',
data: {
entryId: this.entry.id,
},
});
dialogRef.afterClosed().subscribe((result) => {
console.log('Modal Closed: ', result);
});
}
}
refrechEntry() {
this.lockActions = true;
this.entryService.refrechEntryById(this.entry.id).subscribe({
next: (entry) => {
this.entry = entry;
// console.log(`Entry refreched: `, entry);
// TODO show updated notification
},
error: (error) => {
// TODO show error notification
console.error('Error refreching movie info:', error);
},
complete: () => {
this.lockActions = false;
},
});
}
// ! EPISODE SEEN
// ? episode marked as seen event
onEpisodeWatchedEvent() {
this.getEpisodesSeenHistory();
}
// ? fetch episodes seen history
getEpisodesSeenHistory() {
if (!this.entry.is_tvseries) return;
this.episodeSeenService.getEpisodeSeenByEntryId(this.entry.id).subscribe({
next: (data) => {
let episodeSeens = [] as EpisodeSeenDto[];
// mapping
data.forEach((item) => {
let e = {
id: item.id,
entryId: item.entry_id,
episodeId: item.episode_id,
season_number: item.episode.season.season_number,
episode_number: item.episode.episode_number,
date_seen: item.date_seen,
seen_with: item.seen_with,
createdAt: item.createdAt,
updatedAt: item.updatedAt,
} as EpisodeSeenDto;
episodeSeens.push(e);
});
this.seenHistory = episodeSeens;
// console.log(`Episode Seen History Received: `, episodeSeens);
this.filterEpisodesSeenHistory();
},
error: (error) => {
this.seenHistory = [] as EpisodeSeenDto[];
this.filterEpisodesSeenHistory();
console.log(`Error getting episodes watch history`, error);
},
});
}
// ? filter episode seen history
filterEpisodesSeenHistory() {
var temp = [] as EpisodeSeenDto[];
temp = this.seenHistory;
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
this.itemsCount = temp.length;
this.maxPage = Math.ceil(this.itemsCount / this.pageSize);
this.seenHistoryToShow = temp.slice(startIndex, endIndex);
}
editEpisodeSeen(episodeSeen: EpisodeSeenDto) {
if (episodeSeen == null) return;
const dialogRef = this.dialog.open(SeenModalComponent, {
width: '360px',
data: {
watchDate: episodeSeen.date_seen,
watchedWith: episodeSeen.seen_with,
},
});
dialogRef.afterClosed().subscribe((result) => {
// ? dialog closed
if (result == null) return;
// ? dialog confimed
// console.log('Episode seen dialog closed with:', result);
if (result.watchDate == '') {
// TODO show no date was passed notification
return console.log(`Episode seen dialog closed with no date.`);
}
episodeSeen.date_seen = result.watchDate;
episodeSeen.seen_with = result.watchedWith.split('\n').join(', ');
this.episodeSeenService.updateEpisodeSeen(episodeSeen).subscribe({
next: () => {
// console.log(`Episode seen updated.`);
this.getEpisodesSeenHistory();
// TODO show notification
},
error: (error) => {
console.log(`Episode seen update error: `, error);
// TODO show notification
},
});
});
}
deleteEpisodeSeen(episodeSeen: EpisodeSeenDto) {
if (episodeSeen.id == null) return;
const dialogRef = this.dialog.open(ConfirmModalComponent, {
width: '400px',
data: {
title: 'Confirmation',
message: `Are you sure you want to delete this?`,
type: 'danger',
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
console.log(result);
if (result.confirmed != true) return;
// first start by calling the service and deleting the episode-seen
this.episodeSeenService.removeEpisodeSeen(episodeSeen.id).subscribe({
next: () => {
// console.log(`Episode seen deleted.`);
// call this function to fetch the new episode-seen history
this.getEpisodesSeenHistory();
// trying to update the episodes seen progress bar in the season card
// by fetching a new updated episodes list
this.entry.seasons.forEach(async (season) => {
if (season.season_number == episodeSeen.season_number) {
this.seasonService.getSeasonEpisodes(season.id).subscribe({
next: (episodes) => {
// console.log(
// `Loaded Season ${season.season_number} Episodes (${episodes.length})`
// );
season.episodes = episodes;
},
error: (error) => {
console.log(`Couldn't fetch season episodes data:`, error);
// TODO show notification
season.episodes = [];
},
});
}
});
// TODO show notification
},
error: (error) => {
console.log(`Episode seen delete error: `, error);
},
});
}
});
}
triggerEpisodeWatchedDeletedEvent() {
console.log(`Emitted Episode Watched Deleted Event`);
}
// + end EPISODE SEEN
// ! pagination
goToPage(page: number) {
this.currentPage = page;
this.filterEpisodesSeenHistory();
}
get pageNumbers(): number[] {
let pagesToShow = 5; // Total pages to show at any time
let startPage: number, endPage: number;
if (this.maxPage <= pagesToShow) {
startPage = 1;
endPage = this.maxPage;
} else {
startPage = Math.max(this.currentPage - Math.floor(pagesToShow / 2), 1);
endPage = startPage + pagesToShow - 1;
if (endPage >= this.maxPage) {
endPage = this.maxPage;
startPage = endPage - pagesToShow + 1;
}
}
// Generate the page numbers array.
return Array.from(
{ length: endPage - startPage + 1 },
(_, i) => startPage + i
);
}
// + end pagination
toggleShowAllSeasons() {
this.showAll = !this.showAll;
}
enlargePoster() {
window.open(
'https://image.tmdb.org/t/p/original' + this.entry.poster_path,
'_blank'
);
}
// * getters
get status() {
return this.entry.status;
}
get runtime() {
return this.entry.runtime;
}
get genres(): string {
return this.entry.genres.join(', ');
}
get poster(): string {
if (this.entry.poster_path == null)
return 'assets/images/default/default-poster.png';
return `https://image.tmdb.org/t/p/w500` + this.entry.poster_path;
}
get banner(): string {
if (this.entry.banner_path == null)
return 'assets/images/default/default-poster.png';
return `https://image.tmdb.org/t/p/w1280` + this.entry.banner_path;
}
get nextEpisode() {
if (!this.entry.is_tvseries) return 'This is a movie';
return 'sooon';
}
}