import { Injectable } from "@angular/core" ; import { Connector } from "../connector.service" ; import { UserDto } from "./user.dto" ; import { UserVo } from "./user.vo" ; import { LayoutBoxDto , LayoutDto } from "./layout.dto" ; @ Injectable ( ) export class UserService { private userPreferences : Map < string , string > ; constructor ( private connector ) { } private mapToString ( map ) { let obj = { } ; map . forEach ( ( value , key ) => obj [ key ] = value ) ; return JSON . stringify ( obj ) ; } private strToMap ( value ) { let map = new Map < string , string > ( ) ; let obj ; try { obj = JSON . parse ( value ) ; } catch ( e ) { obj = { } ; } for ( let k in obj ) { if ( k === undefined ) continue ; map . set ( k , obj [ k ] ) ; } return map ; } getUserPreferences ( ) { return new Promise < Map < string , string > > ( ( resolve , reject ) => { if ( this . userPreferences ) return resolve ( this . userPreferences ) ; this . userPreferences = this . strToMap ( window . localStorage . getItem ( "user_preferences" ) ) ; if ( ! this . userPreferences ) this . userPreferences = new Map < string , string > ( ) ; resolve ( this . userPreferences ) ; } ) ; } updateUserPreferences ( key , value ) { return new Promise < void > ( ( resolve , reject ) => { this . userPreferences . set ( key , value ) ; window . localStorage . setItem ( "user_preferences" , this . mapToString ( this . userPreferences ) ) ; resolve ( ) ; } ) ; } getUserLayouts ( ) { return this . getUserPreferences ( ) . then ( ( preferences ) => { let rawLayoutsData = preferences . get ( "layouts" ) ; let rawLayouts = rawLayoutsData !== undefined ? JSON . parse ( rawLayoutsData ) : [ ] ; return rawLayouts . map ( LayoutDto . parse ) ; } ) ; } saveLayout ( layout ) { return this . getUserLayouts ( ) . then ( ( layouts ) => { let found = layouts . find ( ( i ) => i . name === layout . name ) ; if ( found ) { found . boxes = layout . boxes ; found . nodes = layout . nodes ; } else { layouts . push ( layout ) ; } return this . updateUserPreferences ( "layouts" , JSON . stringify ( layouts . map ( ( i ) => i . stringify ( ) ) ) ) ; } ) ; } deleteLayout ( layoutName ) { return this . getUserLayouts ( ) . then ( ( layouts ) => { let found = layouts . findIndex ( ( i ) => i . name === layoutName ) ; layouts . splice ( found , 1 ) ; return this . updateUserPreferences ( "layouts" , JSON . stringify ( layouts . map ( ( i ) => i . stringify ( ) ) ) ) ; } ) ; } }