import { Events } from 'ionic-angular' ; import { Component , Input } from '@angular/core' ; import { Line } from '../../models/itinerary' ; import { FavoritesDAO } from '../../dao/favorites' ; import { Analytics } from '../../core/analytics' ; class @ Component ( { selector : 'favorite-button' , templateUrl : 'template.html' , } ) export class FavoriteButton { @ Input ( ) public line : Line ; @ Input ( ) public size : string ; private favorites : Line [ ] ; private static isBusy : boolean = false ; public constructor ( private events , private dao ) { this . favorites = [ ] ; this . updateState ( ) ; this . events . subscribe ( 'update:favorites' , ( ) => this . updateState ( ) ) ; } public isFavorite ( ) { return this . favorites . some ( favorite => favorite . Line === this . line . Line ) || false ; } private return { void } private updateState ( ) { this . dao . getAll ( ) . then ( favorites => this . favorites = favorites ) ; } return { void } public onClick ( ) { if ( ! FavoriteButton . isBusy ) { FavoriteButton . isBusy = true ; if ( this . isFavorite ( ) ) this . dao . remove ( this . line ) . then ( ( response ) => this . onUnstar ( response ) ) ; else this . dao . save ( this . line ) . then ( ( response ) => this . onStar ( response ) ) ; } } private param { boolean } response return { void } private onStar ( response ) { console . log ( 'Starring...' ) ; Analytics . trackEvent ( 'Favorite button' , 'star' , 'add to favorites' ) ; if ( response ) this . events . publish ( 'update:favorites' ) ; else console . log ( `Failed to star the line '${ this . line . Line }'` ) ; FavoriteButton . isBusy = false ; } private param { boolean } response return { void } private onUnstar ( response ) { console . log ( 'Unstarring...' ) ; Analytics . trackEvent ( 'Favorite button' , 'unstar' , 'remove from favorites' ) ; if ( response ) this . events . publish ( 'update:favorites' ) ; else console . log ( `Failed to unstar the line '${ this . line . Line }'` ) ; FavoriteButton . isBusy = false ; } }