import { Injectable } from "@angular/core" ; import { State , Action , StateContext , Selector , Store } from "@ngxs/store" ; import { catchError , tap } from "rxjs/operators" ; import { ApiService , StylingService } from "@app/core" ; import { Config } from "./config.actions" ; import { ConfigStateModel } from "./config.model" ; import { of } from "rxjs" ; import { Product } from "../product" ; @ State < ConfigStateModel > ( { name : "config" , defaults : { dataUrl : "" , stylingUrl : "" , styleOptions : [ ] , staticText : undefined , } , } ) @ Injectable ( ) export class ConfigState { constructor ( private apiService , private stylingService , private store ) { } @ Action ( Config . UpdateDataUrl ) updateDataUrl ( ctx , action ) { const state = ctx . getState ( ) ; if ( action . url ) { ctx . setState ( { ... state , dataUrl : action . url , } ) ; this . store . dispatch ( new Product . LoadCategories ( action . url ) ) . toPromise ( ) . then ( ( ) => this . store . dispatch ( new Product . LoadProductGroups ( action . url ) ) ) ; return ctx . dispatch ( [ new Config . UpdateStaticText ( ) ] ) ; } } @ Action ( Config . UpdateStylingUrl ) updateStylingUrl ( ctx , action ) { const state = ctx . getState ( ) ; if ( action . url ) { ctx . setState ( { ... state , stylingUrl : action . url , } ) ; return this . apiService . getRemoteStyles$ ( action . url ) . pipe ( tap ( ( style ) => { this . stylingService . updateAppCSS ( style ) ; } ) , catchError ( ( err ) => { console . log ( "error loading remote style" , err ) ; return of ( err ) ; } ) ) ; } } @ Action ( Config . UpdateStyleOptions ) updateStyleOptions ( ctx , action ) { const state = ctx . getState ( ) ; return this . apiService . getRemoteStylesOptions$ ( ) . pipe ( tap ( ( styleOptions ) => { ctx . setState ( { ... state , styleOptions : styleOptions , } ) ; } ) , catchError ( ( err ) => { console . log ( "error loading style options" , err ) ; return of ( err ) ; } ) ) ; } @ Action ( Config . UpdateStaticText ) updateStaticText ( ctx ) { const state = ctx . getState ( ) ; return this . apiService . getStaticText$ ( state . dataUrl ) . pipe ( tap ( ( staticText ) => { ctx . setState ( { ... state , staticText : staticText , } ) ; } ) , catchError ( ( err ) => { console . log ( "error loading static text" , err ) ; return of ( err ) ; } ) ) ; } @ Selector ( ) static dataUrl ( state ) { return state . dataUrl ; } @ Selector ( ) static stylingUrl ( state ) { return state . stylingUrl ; } @ Selector ( ) static staticText ( state ) { return state . staticText ; } @ Selector ( ) static styleOptions ( state ) { return state . styleOptions ; } }