// 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/Observable';
// libs
import { Store } from '@ngrx/store';
// app
import { QueryAction, SetEntriesAction } from '../actions/loop-trending-activity.action';
import { APIDispatcher, APIRequestOptions, ResponseBody } from '../utils/index';

@Injectable()
export class LoopTrendingActivityService extends APIDispatcher {

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

    query(
        page: number = 0,
        size: number = 10,
        options: APIRequestOptions = {
            sortBy: 'view_count',
            sortDir: 'DESC',
            filter: 'all'
    }): Observable<any> {
        return this.get('ma_loop/api/v1/trending/fetch', page, size, options)
            .map(res => res.json())
            .catch(this.handleError);
    }

    queryForStore(
        page: number = 0,
        size: number = 10,
        options: APIRequestOptions = {
            sortBy: 'view_count',
            sortDir: 'DESC',
            filter: 'all'
    }): any {
        return this.get('ma_loop/api/v1/trending/fetch', page, size, options)
            .map(res => res.json())
            .catch(this.handleError)
            .subscribe((response: ResponseBody)  => {
                this.store.dispatch(new QueryAction(response.content));
            });
    }
    /**
     * Queries the next page from the back-end service, based on the previous request
     *
     *
     * @memberOf LoopTrendingActivityService
     */
    getNextPage() {
        if(this.hasNext) {
            this.query(this.lastRequest.currentPage + 1, this.lastRequest.requestSize);
        }
    }

    /**
     * Resets the entries in the app-state slice for LoopActivity
     *
     *
     * @memberOf LoopTrendingActivityService
     */
    resetEntries() {
        this.loaded = false;
        this.lastRequest = undefined;
        this.store.dispatch(new SetEntriesAction([]));
    }

}

