import { LoadingService } from './../../core/loading.service';
import { HttpClient } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { REQUEST_ATTACKS_LIST, SetAttacksListAction } from "./attacks.actions";
import { map, switchMap, catchError, finalize } from "rxjs/operators";
import { empty } from 'rxjs';
import { Attack } from '../model/attack.model';

@Injectable()
export class AttacksEffects{

    @Effect()
    requestAttacksList = this.actions.pipe(
        ofType(REQUEST_ATTACKS_LIST),
        switchMap(
            () => {
                this.loadingService.enableLoading();
                return this.http.get('/tadis/attacks').pipe( 
                    map(
                        (attacks: Attack[]) => {
                            return new SetAttacksListAction(attacks);
                        }
                    ),
                    catchError(() => { return empty(); }),
                    finalize(() => { this.loadingService.disableLoading(); })
                );
            }
        ),

    );

    constructor(
        private actions: Actions, 
        private http: HttpClient,
        private loadingService: LoadingService
    ) {}
}