import { Injectable } from '@angular/core';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, exhaustMap, map, tap } from 'rxjs/operators';

import { MetaSensorDisplayMapping, MetaSensorDisplayItem, MetaSensorItemKey } from '@overflow/commons-typescript/model/meta';

import { MetaSensorDisplayMappingService } from '../../../service/meta-sensor-display-mapping.service';

import {
  ReadAllMetaSensorItemKeyByDisplayItem,
  ReadAllMetaSensorItemKeyByDisplayItemSuccess,
  ReadAllMetaSensorItemKeyByDisplayItemFailure,
  ActionType,
} from './meta-sensor-display-mapping.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaSensorDisplayMappingService: MetaSensorDisplayMappingService,
  ) { }

  @Effect()
  readAllMetaSensorItemKeyByDisplayItem$ = this.actions$.pipe(
    ofType(ActionType.ReadAllMetaSensorItemKeyByDisplayItem),
    map((action: ReadAllMetaSensorItemKeyByDisplayItem) => action.payload),
    exhaustMap((metaSensorDisplayItem: MetaSensorDisplayItem) =>
      this.metaSensorDisplayMappingService
        .readAllMetaSensorItemKeyByDisplayItem(metaSensorDisplayItem)
        .pipe(
          map((result: MetaSensorItemKey[]) => {
            return new ReadAllMetaSensorItemKeyByDisplayItemSuccess(result);
          }),
          catchError(error => of(new ReadAllMetaSensorItemKeyByDisplayItemFailure(error)))
        )
    )
  );
}
