import { Line } from '../models/itinerary' ; import { History } from '../models/history' ; import { Storage } from '@ionic/storage' ; import { Injectable } from '@angular/core' ; class @ Injectable ( ) export class HistoryDAO { private collectionName : string = 'history' ; public constructor ( private storage ) { } private return { Promise < History [ ] > } private get Storage ( ) : Promise < History [ ] > { return new Promise < History [ ] > ( ( resolve ) => { this . storage . get ( this . collectionName ) . then ( ( content ) => { if ( ! content ) resolve ( [ ] ) ; else { let list = JSON . parse ( content ) ; let output = [ ] ; list . forEach ( data => { let line = new Line ( data . line . line , data . line . description ) ; output . push ( new History ( line , new Date ( data . timestamp ) , data . timesSearched ) ) ; } ) ; resolve ( this . sort ( output ) ) ; } } ) ; } ) ; } private param { History [ ] } objs return { Promise < any > } private set ( objs ) { return this . storage . set ( this . collectionName , JSON . stringify ( objs ) ) ; } param { History } obj return { Promise < boolean > } public save ( obj ) { return new Promise < boolean > ( ( resolve , reject ) => { this . Storage . then ( ( histories ) => { let tmpDate = new Date ( ) ; let index = histories . findIndex ( data => data . Line . Line === obj . Line . Line && data . Timestamp . getDate ( ) === tmpDate . getDate ( ) && data . Timestamp . getMonth ( ) === tmpDate . getMonth ( ) && data . Timestamp . getFullYear ( ) === tmpDate . getFullYear ( ) ) ; if ( index > - 1 ) histories [ index ] . incrementCounter ( ) ; else histories . push ( obj ) ; this . set ( histories ) . then ( ( ) => resolve ( true ) ) ; } ) ; } ) ; } param { History } obj return { Promise < boolean > } public remove ( obj ) { return new Promise < boolean > ( ( resolve , reject ) => { this . Storage . then ( ( histories ) => { let exists = histories . some ( data => data . Line . Line === obj . Line . Line ) ; if ( ! exists ) resolve ( false ) ; else { let index = histories . findIndex ( ( history ) => history . Line . Line === obj . Line . Line ) ; histories . splice ( index , 1 ) ; this . set ( histories ) . then ( ( ) => resolve ( true ) ) ; } } ) ; } ) ; } return { Promise < void > } public clear ( ) { return this . set ( [ ] ) ; } return { Promise < History [ ] > } public getAll ( ) { return this . Storage ; } param { number } size return { Promise < History [ ] > } public getLimited ( size ) { return this . Storage . then ( histories => histories . splice ( 0 , size ) ) ; } private param { History [ ] } histories return { History [ ] } private sort ( histories ) { return histories . sort ( ( a , b ) => { let newer = b . Timestamp . getTime ( ) - a . Timestamp . getTime ( ) ; newer = newer && newer / Math . abs ( newer ) ; let heavier = b . count - a . count ; return newer + heavier ; } ) ; } }