import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { TenantsService } from '@iqser/common-ui';

const LAST_DOSSIERS_SCREEN = 'routerHistory_lastDossiersScreen';

@Injectable({
    providedIn: 'root',
})
export class RouterHistoryService {
    private _lastDossiersScreen = localStorage.getItem(LAST_DOSSIERS_SCREEN);

    constructor(private readonly _router: Router, private readonly _tenantsService: TenantsService) {
        // eslint-disable-next-line rxjs/no-ignored-subscription
        this._router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
            if (event.url.includes('/dossiers') || event.url.includes('/archive')) {
                this._lastDossiersScreen = event.url;
                localStorage.setItem(LAST_DOSSIERS_SCREEN, this._lastDossiersScreen);
            }
        });
    }

    navigateToLastDossiersScreen(): void {
        if (this._router.url === decodeURI(this._lastDossiersScreen)) {
            this._router.navigate(['/' + this._tenantsService.activeTenantId]);
        } else {
            const url = decodeURI(this._lastDossiersScreen).split('?')[0];
            // todo links
            this._router.navigate([url]);
        }
    }
}
