1 import { OnDestroy, OnInit } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
4 import { NotificationsService } from 'angular2-notifications'
5 import { Observable } from 'rxjs/Observable'
6 import { Subscription } from 'rxjs/Subscription'
8 import { SortField, Video, VideoPagination } from '../../shared'
10 export abstract class AbstractVideoList implements OnInit, OnDestroy {
11 pagination: VideoPagination = {
16 sort: SortField = '-createdAt'
19 protected notificationsService: NotificationsService
20 protected router: Router
21 protected route: ActivatedRoute
22 protected subActivatedRoute: Subscription
24 protected abstract currentRoute: string
26 abstract titlePage: string
27 private loadedPages: { [ id: number ]: boolean } = {}
29 abstract getVideosObservable (): Observable<{ videos: Video[], totalVideos: number}>
32 // Subscribe to route changes
33 const routeParams = this.route.snapshot.params
34 this.loadRouteParams(routeParams)
35 this.loadMoreVideos('after')
39 this.subActivatedRoute.unsubscribe()
43 if (this.pagination.currentPage > 1) {
49 if (this.hasMoreVideos()) {
54 loadMoreVideos (where: 'before' | 'after') {
55 if (this.loadedPages[this.pagination.currentPage] === true) return
57 const observable = this.getVideosObservable()
60 ({ videos, totalVideos }) => {
61 this.loadedPages[this.pagination.currentPage] = true
62 this.pagination.totalItems = totalVideos
64 if (where === 'before') {
65 this.videos = videos.concat(this.videos)
67 this.videos = this.videos.concat(videos)
70 error => this.notificationsService.error('Error', error.text)
74 protected hasMoreVideos () {
75 if (!this.pagination.totalItems) return true
77 const maxPage = this.pagination.totalItems/this.pagination.itemsPerPage
78 return maxPage > this.pagination.currentPage
81 protected previousPage () {
82 this.pagination.currentPage--
84 this.setNewRouteParams()
85 this.loadMoreVideos('before')
88 protected nextPage () {
89 this.pagination.currentPage++
91 this.setNewRouteParams()
92 this.loadMoreVideos('after')
95 protected buildRouteParams () {
96 // There is always a sort and a current page
99 page: this.pagination.currentPage
105 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
106 this.sort = routeParams['sort'] as SortField || '-createdAt'
108 if (routeParams['page'] !== undefined) {
109 this.pagination.currentPage = parseInt(routeParams['page'], 10)
111 this.pagination.currentPage = 1
115 protected setNewRouteParams () {
116 const routeParams = this.buildRouteParams()
117 this.router.navigate([ this.currentRoute, routeParams ])