import { Component, Renderer2, ViewContainerRef } from '@angular/core';
import { RouterHistoryService } from '@services/router-history.service';
import { UserPreferenceService } from '@users/user-preference.service';
import { getConfig } from '@iqser/common-ui';
import { AppConfig } from '@red/domain';
import { NavigationEnd, Router } from '@angular/router';
import { filter, map, switchMap, take } from 'rxjs/operators';

function loadCustomTheme() {
    const cssFileName = getConfig<AppConfig>().THEME;

    if (cssFileName) {
        const head = document.getElementsByTagName('head')[0];
        const link = document.createElement('link');
        link.id = cssFileName;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = 'assets/styles/themes/' + cssFileName + '.css';
        link.media = 'all';
        head.appendChild(link);
    }
}

@Component({
    selector: 'redaction-root',
    templateUrl: './app.component.html',
})
export class AppComponent {
    constructor(
        /** ViewContainerRef needs to be injected for the color picker to work */
        readonly viewContainerRef: ViewContainerRef,
        /** RouterHistoryService needs to be injected for last dossiers screen to be updated on first app load */
        private readonly _routerHistoryService: RouterHistoryService,
        userPreferenceService: UserPreferenceService,
        renderer: Renderer2,
        private readonly _router: Router,
    ) {
        renderer.addClass(document.body, userPreferenceService.getTheme());
        loadCustomTheme();

        const removeQueryParams = _router.events.pipe(
            filter((event): event is NavigationEnd => event instanceof NavigationEnd),
            map(event => event.urlAfterRedirects),
            filter(url => url.includes('code=') || url.includes('state=') || url.includes('session_state=')),
            switchMap(() => this.#removeKeycloakQueryParams()),
            take(1),
        );
        removeQueryParams.subscribe();

        if (getConfig().IS_DOCUMINE) {
            document.getElementById('favicon').setAttribute('href', 'assets/icons/documine-logo.ico');
        }
    }

    #removeKeycloakQueryParams() {
        return this._router.navigate([], {
            queryParams: {
                state: null,
                session_state: null,
                code: null,
            },
            queryParamsHandling: 'merge',
        });
    }
}
