// angular
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
// libs
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
// app
import { QueryAction, SetEntriesAction, SetSelectedAction } from '../actions/loop-topic.action';
import { APIDispatcher, APIRequestOptions, ResponseBody } from '../utils/index';

@Injectable()
export class LoopTopicService extends APIDispatcher {

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

    query(page: number = 0, size: number = 10, options: APIRequestOptions = {}): Observable<any> {
        return Observable.create((observer: any) => {
            if(this.lastRequest) {
                if(this.lastRequest.options !== options) {
                    this.lastRequest.currentPage = page;
                    this.lastRequest.requestSize = size;
                    this.lastRequest.options = options;
                }
            }
            this.get('ma_loop/api/v3/objections/fetch', page, size, options).map(res => res.json())
                .catch(this.handleError)
                .subscribe((response: ResponseBody) => {
                    this.loaded = true;
                    this.lastRequest = response;
                    this.lastRequest.currentPage = page;
                    this.lastRequest.requestSize = size;
                    this.lastRequest.options = options;
                    this.store.dispatch(new QueryAction(response.content));
                    observer.next(response);
                    observer.complete();
                });
        });
    }

    fetch(identities: string[]): Observable<any> {
        return this.post('ma_loop/api/v3/objections/fetch', identities)
            .map(res => res.json())
            .catch(this.handleError);
    }

    fetchForStore(identities: string[]): any {
        return this.fetch(identities).subscribe((response: ResponseBody) => {
            this.loaded = true;
            this.store.dispatch(new QueryAction(response.content));
        });
    }

    notes(identities: string[]): any {
        return this.http.post('ma_loop/api/v3/objections/notes', identities);
    }

    responses(identities: string[]): any {
        return this.http.post('ma_loop/api/v3/objections/rebuttals', identities);
    }

    updateNote(identity: string, note: string): any {
        return this.http.post('ma_loop/api/v3/objections/'+identity+'/note', note);
    }


    /**
     * Fetches the next available page for topics, if any
     */
    getNextPage() {
        if(this.hasNext && !this.fetchingNext) {
            this.fetchingNext = true;
            this.query(this.lastRequest.currentPage + 1, this.lastRequest.requestSize, this.lastRequest.options).subscribe(() => {
                this.fetchingNext = false;
            });
        }
    }

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

    /**
     * Resets the selected entries in the app-state slice for Loop Topics
     *
     *
     * @memberOf LoopTopicService
     */
    resetSelectedEntries() {
        this.store.dispatch(new SetSelectedAction([]));
    }

}

