import { Injectable , Inject } from "@angular/core" ; import { Subject } from "rxjs" ; import { Router } from "@angular/router" ; declare let swellrt ; @ Injectable ( ) export class BackendService { service : Promise < any > ; session : Promise < any > ; bind ( service ) { this . service = service ; } get ( ) { return this . service ; } startUserSession ( id , password ) { } startDefaultSession ( ) { this . session = this . service . then ( s => { return s . resume ( { } ) ; } ) . then ( u => { console . log ( "Session resumed for user " + u . toString ( ) ) ; return u ; } ) . catch ( e => { console . log ( "No resumable session" ) ; return this . startAnonymousSession ( ) ; } ) ; return this . session ; } private startAnonymousSession ( ) { return this . service . then ( s => { return s . login ( { id : swellrt . Service . ANONYMOUS_USER_ID , password : "" } ) ; } ) . then ( u => { console . log ( "Anonymous session started" ) ; return u ; } ) . catch ( e => { console . log ( "Anonymous session couldn't be started: " + e . toString ( ) ) ; throw e ; } ) ; } open ( id ) { console . log ( "Opening document " + id ) ; return this . session . then ( u => { return this . service ; } ) . then ( s => { return s . open ( { id : id } ) ; } ) ; } close ( id ) { console . log ( "Closing document " + id ) ; this . service . then ( s => { return s . close ( id ) ; } ) ; } static initDocObject ( doc , docid ) { let title = doc . get ( "title" ) ; let text = doc . get ( "text" ) ; let isNew = ! title || ! text ; if ( ! title ) { doc . put ( "title" , BackendService . docIdToTitle ( docid ) ) ; } if ( ! text ) { doc . put ( "text" , swellrt . Text . create ( "" ) ) ; } if ( isNew ) { doc . setPublic ( true ) ; } let comments = doc . get ( "comments" ) ; if ( ! comments ) { doc . put ( "comments" , swellrt . Map . create ( ) ) ; } } static docNameToId ( name ) { } static docIdToTitle ( id ) { let s = id . replace ( '-' , ' ' ) ; return s . charAt ( 0 ) . toUpperCase ( ) + s . slice ( 1 ) ; } }