import { Line } from '../models/itinerary' ; import { Storage } from '@ionic/storage' ; import { Injectable } from '@angular/core' ; class @ Injectable ( ) export class LinesDAO { private collectionName : string = 'lines' ; public constructor ( private storage ) { } private return { Promise < Line [ ] > } private get Storage ( ) : Promise < Line [ ] > { return new Promise < Line [ ] > ( ( resolve ) => { this . storage . get ( this . collectionName ) . then ( ( content ) => { if ( ! content ) resolve ( [ ] ) ; else { let list = JSON . parse ( content ) ; let output = [ ] ; list . forEach ( data => output . push ( new Line ( data . line , data . description ) ) ) ; resolve ( output ) ; } } ) ; } ) ; } private param { Line [ ] } objs return { Promise < void > } private set ( objs ) { return this . storage . set ( this . collectionName , JSON . stringify ( objs ) ) ; } param { Line } obj return { Promise < boolean > } public save ( obj ) { return new Promise < boolean > ( ( resolve , reject ) => { this . Storage . then ( ( lines ) => { let exists = lines . some ( data => data . Line === obj . Line ) ; if ( exists ) resolve ( false ) ; else { lines . push ( obj ) ; this . set ( lines ) . then ( ( ) => resolve ( true ) ) ; } } ) ; } ) ; } param { Line [ ] } lines return { Promise < void > } public saveAll ( lines ) { return this . set ( lines ) ; } param { Line } obj return { Promise < boolean > } public remove ( obj ) { return new Promise < boolean > ( ( resolve , reject ) => { this . Storage . then ( ( lines ) => { let exists = lines . some ( data => data . Line === obj . Line ) ; if ( ! exists ) resolve ( false ) ; else { let index = lines . findIndex ( ( line ) => line . Line === obj . Line ) ; lines . splice ( index , 1 ) ; this . set ( lines ) . then ( ( ) => resolve ( true ) ) ; } } ) ; } ) ; } return { Promise < Line [ ] > } public getAll ( ) { return this . Storage ; } param { number } size param { number } skip return { Promise < Line [ ] > } public getLimited ( limit , skip = 0 ) { return this . getAll ( ) . then ( lines => { return this . sort ( lines ) . splice ( skip , limit ) ; } ) ; } 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 ; } ) ; } }