import { APP_BASE_HREF } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { WINDOW } from '@app/shared/services';

@Component({
    selector: 'error-page',
    templateUrl: './error-page.component.html',
    styleUrls: ['./error-page.component.scss'],
})
export class ErrorPageComponent implements OnInit, OnDestroy {
    aflComponentsDisplays: string[];
    errorCode = '500';
    title = '';
    description = '';
    searchTerm: string;

    constructor(
        @Inject(APP_BASE_HREF) public baseHref: string,
        private route: ActivatedRoute,
        @Inject(WINDOW) private window$: Window,
    ) {}

    ngOnInit() {
        const { title, errorCode, description } = this.route.snapshot.data;

        this.title = title;
        this.errorCode = errorCode;
        this.description = description;

        this.hideAflComponents();
    }

    ngOnDestroy() {
        this.showAflComponents();
    }

    search() {
        const url = `https://www.aeroflot.ru${this.baseHref}/search?text=${this.searchTerm}`;
        this.window$.open(url, '_blank');
    }

    private hideAflComponents() {
        const components =
            document.querySelectorAll<HTMLElement>('.afl-component--banners');
        this.aflComponentsDisplays = Array.from(components).map((component) => {
            return component.style.display;
        });

        components.forEach((component) => {
            component.style.display = 'none';
        });
    }

    private showAflComponents() {
        const components =
            document.querySelectorAll<HTMLElement>('.afl-component--banners');
        components.forEach((component, index) => {
            component.style.display = this.aflComponentsDisplays[index] || '';
        });
    }
}
