// angular
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
// libs
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs';
import { Store, } from '@ngrx/store';
// app
import { LoopUser } from '../interfaces/index';
import { APIDispatcher } from '../utils/index';
import {
    AuthAction,
    EntriesAction
} from '../actions/loop-user.action';

@Injectable()
export class LoopUserService extends APIDispatcher {

    constructor(public http: Http, public store: Store<any>) {
        super(http, store);
    }

    getAuthorizedUser(): any {
        return this.http.get('ma_loop/api/v1/users/current/').map(res => res.json())
            .subscribe((authUser: LoopUser) => {
                this.store.dispatch(new AuthAction(authUser));
            });
    }

    query(): any {
        return this.http.get('ma_loop/api/v1/users/fetch').map(res => res.json())
            .subscribe((users: LoopUser[]) => {
                this.store.dispatch(new EntriesAction(users));
            });
    }

    fetchAvatars(userIdentities: string[]) {
        return Observable.create((observer: any) => {
            this.http.post('ma_loop/api/v1/users/thumbnails', userIdentities).map(res => res.json())
                .subscribe((response: LoopUser[]) => {
                    observer.next(response);
                    observer.complete();
                });
        });
    }

}
