import { Injectable } from '@angular/core';
import { Effect, Actions } from '@ngrx/effects';

import { AppState } from '../reducers';
import { CategoryActions } from '../actions';
import { EcmCategoryService } from '../../ecm-view/ecm-category/ecm-category.service';

@Injectable()
export class CategoryEffects {
    constructor (
        private update$: Actions,
        private catgoryActions: CategoryActions,
        private svc: EcmCategoryService,
    ) {}

    @Effect() loadCategories$ = this.update$
        .ofType(CategoryActions.LOAD_CATEGORY)
        .switchMap(() => this.svc.getCategories())
        .map(categories => this.catgoryActions.loadCategoriesSuccess(categories));
    
    @Effect() getCategory$ = this.update$
        .ofType(CategoryActions.GET_CATEGORY)
        .switchMap(catCode => this.svc.getCategory(catCode.payload))
        .map(category => this.catgoryActions.getCategorySuccess(category));
}
