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

import {AppState} from '../reducers';
import {SubCategoryActions} from '../actions';
import { EcmSubCategoryService } from '../../ecm-view/ecm-sub-category/ecm-sub-category.service';

@Injectable()
export class SubCategoryEffects {
    constructor (
        private update$: Actions,
        private subCategoryActions: SubCategoryActions,
        private svc: EcmSubCategoryService,
    ) {}

    @Effect() loadCategories$ = this.update$
        .ofType(SubCategoryActions.LOAD_SUBCATEGORY)
        .switchMap(catCode => this.svc.getSubCategories(catCode.payload))
        .map(subcategories => this.subCategoryActions.loadSubCategoriesSuccess(subcategories));

    @Effect() getSubCategory$ = this.update$
        .ofType(SubCategoryActions.GET_SUBCATEGORY)
        .switchMap(scatCode => this.svc.getSubCategory(scatCode.payload))
        .map(subcategory => this.subCategoryActions.getSubCategorySuccess(subcategory));
}