import * as _ from 'lodash';
import * as queryString from 'query-string';
import { Observable } from 'rxjs';
import { Event } from './event.service';

class HttpEventService {
    private hashObservable = new Event();

    private queryObservable = new Event();

    private query = new Event();

    public firstPage = true;

    public lastUrl = null;

    constructor() {
        this.hashObservable.set(window.location.hash);
        this.queryObservable.set(queryString.parseUrl(window.location.href).query);

        setInterval(() => {
            // Hash
            if (this.hashObservable.snapshot !== window.location.hash) {
                this.firstPage = false;
                this.hashObservable.set(window.location.hash);
            }

            // Query
            if (!_.isEqual(this.queryObservable.snapshot, queryString.parseUrl(window.location.href).query)) {
                this.queryObservable.set(queryString.parseUrl(window.location.href).query);
            }
        }, 100);
    }

    get hash(): Observable<any> {
        return this.hashObservable.observable;
    }

    getLastUrl(): string {
        return this.lastUrl;
    }

    get queryParams(): Observable<any> {
        return this.queryObservable.observable;
    }
}

export default new HttpEventService();
