import { API_ENDPOINT } from '../const' ; import { Itinerary , Line , Spot } from '../models/itinerary' ; import { Injectable } from '@angular/core' ; import { Http } from '@angular/http' ; class @ Injectable ( ) export class ItineraryService { public constructor ( private http ) { } private param { any } obj return { Itinerary } private processItinerary ( obj ) { let spots = [ ] ; obj . spots . forEach ( ( spot ) => { spots . push ( new Spot ( spot . latitude , spot . longitude , spot . returning ) ) ; } ) ; return new Itinerary ( obj . line , obj . description , obj . agency , spots ) ; } private param { any [ ] } obj return { Line [ ] } private processLines ( obj ) { let result = [ ] ; obj . forEach ( ( data ) => { result . push ( new Line ( data . line , data . description ) ) ; } ) ; return this . sort ( result ) ; } param { string } line return { Promise < Itinerary > } public getItinerary ( line ) { return new Promise < Itinerary > ( ( resolve , reject ) => { let url = `${ API_ENDPOINT }/v3/itinerary/${ line }` ; this . http . get ( url ) . subscribe ( data => resolve ( this . processItinerary ( data . json ( ) ) ) , error => reject ( error ) ) ; } ) ; } return { Promise < Line [ ] > } public getItineraries ( ) { return new Promise < Line [ ] > ( ( resolve , reject ) => { let url = `${ API_ENDPOINT }/v3/itinerary` ; this . http . get ( url ) . subscribe ( data => resolve ( this . processLines ( data . json ( ) ) ) , error => reject ( error ) ) ; } ) ; } private param { Line [ ] } items return { Line [ ] } private sort ( items ) { return items . sort ( ( a , b ) => { if ( ! isNaN ( parseInt ( a . Line ) ) && ! isNaN ( parseInt ( b . Line ) ) ) return ( parseInt ( a . Line ) - parseInt ( b . Line ) ) ; else if ( ! isNaN ( parseInt ( a . Line ) ) && isNaN ( parseInt ( b . Line ) ) ) return - 1 ; else if ( isNaN ( parseInt ( a . Line ) ) && isNaN ( parseInt ( b . Line ) ) ) return 0 ; else return 1 ; } ) ; } }