1 import { OnInit } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
3 import { NotificationsService } from 'angular2-notifications'
4 import { Observable } from 'rxjs/Observable'
5 import { SortField } from './sort-field.type'
6 import { VideoPagination } from './video-pagination.model'
7 import { Video } from './video.model'
9 export abstract class AbstractVideoList implements OnInit {
10 pagination: VideoPagination = {
15 sort: SortField = '-createdAt'
16 defaultSort: SortField = '-createdAt'
20 protected notificationsService: NotificationsService
21 protected router: Router
22 protected route: ActivatedRoute
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)
36 if (this.loadOnInit === true) this.loadMoreVideos('after')
40 if (this.pagination.currentPage > 1) {
46 if (this.hasMoreVideos()) {
54 this.loadMoreVideos('before')
57 loadMoreVideos (where: 'before' | 'after') {
58 if (this.loadedPages[this.pagination.currentPage] === true) return
60 const observable = this.getVideosObservable()
63 ({ videos, totalVideos }) => {
64 // Paging is too high, return to the first one
65 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
66 this.pagination.currentPage = 1
67 this.setNewRouteParams()
68 return this.reloadVideos()
71 this.loadedPages[this.pagination.currentPage] = true
72 this.pagination.totalItems = totalVideos
74 if (where === 'before') {
75 this.videos = videos.concat(this.videos)
77 this.videos = this.videos.concat(videos)
80 error => this.notificationsService.error('Error', error.text)
84 protected hasMoreVideos () {
86 if (this.pagination.totalItems === 0) return false
89 if (!this.pagination.totalItems) return true
91 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
92 return maxPage > this.pagination.currentPage
95 protected previousPage () {
96 this.pagination.currentPage--
98 this.setNewRouteParams()
99 this.loadMoreVideos('before')
102 protected nextPage () {
103 this.pagination.currentPage++
105 this.setNewRouteParams()
106 this.loadMoreVideos('after')
109 protected buildRouteParams () {
110 // There is always a sort and a current page
113 page: this.pagination.currentPage
119 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
120 this.sort = routeParams['sort'] as SortField || this.defaultSort
122 if (routeParams['page'] !== undefined) {
123 this.pagination.currentPage = parseInt(routeParams['page'], 10)
125 this.pagination.currentPage = 1
129 protected setNewRouteParams () {
130 const routeParams = this.buildRouteParams()
131 this.router.navigate([ this.currentRoute, routeParams ])