import { Utils } from './utils' ; import { ITodo , ITodoModel } from './interfaces' ; import { OutlookTasks } from '../services' ; export class TodoModel implements ITodoModel { public key : string ; public todos : Array < ITodo > ; public onChanges : Array < any > ; private _outlookTasks : OutlookTasks ; constructor ( key ) { this . key = key ; this . _outlookTasks = new OutlookTasks ( ) ; this . todos = [ ] ; this . _outlookTasks . get ( ) . then ( tasks => { this . todos = tasks ; this . inform ( ) ; } ) ; this . onChanges = [ ] ; } public subscribe ( onChange ) { this . onChanges . push ( onChange ) ; } public inform ( ) { this . onChanges . forEach ( function ( cb ) { cb ( ) ; } ) ; } public addTodo ( title ) { let todo = { id : Utils . uuid ( ) , title : title , completed : false } ; this . _outlookTasks . create ( todo ) . then ( todo => { this . todos = this . todos . concat ( todo ) ; this . inform ( ) ; } ) ; } public toggleAll ( checked ) { this . todos = this . todos . map < ITodo > ( ( todo ) => { var update = Utils . extend ( { } , todo , { completed : checked } ) ; this . _outlookTasks . update ( update ) ; return update ; } ) ; this . inform ( ) ; } public toggle ( todoToToggle ) { this . todos = this . todos . map < ITodo > ( ( todo ) => { return todo !== todoToToggle ? todo : ( ( ) => { var update = Utils . extend ( { } , todo , { completed : ! todo . completed } ) ; this . _outlookTasks . update ( update ) ; return update ; } ) ( ) ; } ) ; this . inform ( ) ; } public destroy ( todo ) { this . _outlookTasks . delete ( todo ) . then ( result => { if ( result ) { this . todos = this . todos . filter ( function ( candidate ) { return candidate !== todo ; } ) ; } this . inform ( ) ; } ) ; } public save ( todoToSave , text ) { this . todos = this . todos . map ( function ( todo ) { return todo !== todoToSave ? todo : Utils . extend ( { } , todo , { title : text } ) ; } ) ; this . inform ( ) ; } public clearCompleted ( ) { this . todos = this . todos . filter ( todo => { if ( todo . completed ) { this . _outlookTasks . delete ( todo ) ; } return ! todo . completed ; } ) ; this . inform ( ) ; } }