import {Component} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';

import {Observable} from 'rxjs';
import {filter, map, startWith} from 'rxjs/operators';

import {NavigationParams} from 'm2-core';
import {CD_ROUTING, CD_SECTION_REGEX, CD_SECTION_TAB_REGEX} from '../../config';


interface Tab {
    displayName: string;
    routerLink: string;
}

const GROUP_TAB_TEMPLATE: Tab = {
    displayName: $localize`Описание`,
    routerLink: CD_ROUTING.TABS.GROUP
};

const DATA_TAB_TEMPLATES: Tab[] = [
    {
        displayName: $localize`Демо`,
        routerLink: CD_ROUTING.TABS.DEMO
    },
    {
        displayName: $localize`Пример кода`,
        routerLink: CD_ROUTING.TABS.CODE
    },
    {
        displayName: $localize`Описание API`,
        routerLink: CD_ROUTING.TABS.API
    }
];


@Component({
    selector: 'cd-content-tabs',
    template: `
        <sdi-tabs
                class="pt-4"
                [styleClasses]="'form-tabs form-tabs_secondary'"
                [tabRefs]="tabs$ | async"
        >
        </sdi-tabs>
    `
})
export class CdContentTabsComponent {

    constructor(
        private router: Router
    ) {
    }

    private section?: string;
    private fragment?: string;

    tabs$: Observable<NavigationParams[]> = this.router.events
        .pipe(
            filter(e => e instanceof NavigationEnd),
            map((e: NavigationEnd) => e.url),
            startWith(this.router.routerState.snapshot.url),
            map(url => {
                const res = CD_SECTION_REGEX.exec(url);
                return { section: res[1], fragment: res[3], url };
            }),
            filter(({ section, fragment }) => {
                const changed = this.section != section || this.fragment != fragment;
                this.section = section;
                this.fragment = fragment;
                return section != null && changed;
            }),
            // tap(section => console.log(`section changed: ${section}`)),
            map(({ section, fragment, url }) => {
                // TODO it would be better to read actual active cd node type from some service
                // instead of trying to determine it indirectly
                const tab = CD_SECTION_TAB_REGEX.exec(url)?.[1];
                const tabTemplates = tab === CD_ROUTING.TABS.GROUP ?
                    [GROUP_TAB_TEMPLATE] :
                    DATA_TAB_TEMPLATES;

                return tabTemplates
                    .map(t => {
                        const nav = new NavigationParams(`/${CD_ROUTING.BASE}/${section}/${t.routerLink}`,
                            null, null, '_self', false, t.displayName);
                        nav.fragment = fragment;
                        return nav;
                    });
            })
        );


}
