import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';

import {CD_ROUTING, CD_SECTION_TAB_REGEX} from '../config';
import {CdNodeType} from '../components/docs-tree/CdNode';


@Injectable({
    providedIn: 'root'
})
export class CdContentGuardService implements CanActivate {

    constructor(
        private router: Router
    ) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
        const [prevUrl, prevFragment] = decodeURIComponent(this.router.routerState.snapshot.url).split('#');
        const [nextUrl, nextFragment] = state.url.split('#');

        // console.log(prevUrl, ' => ', nextUrl);

        const prevTab = CD_SECTION_TAB_REGEX.exec(prevUrl)?.[1];
        const nextTab = CD_SECTION_TAB_REGEX.exec(nextUrl)?.[1];

        if (route.data.cdNodeType === CdNodeType.group) {
            // for 'group' node there is the only available tab
            return this.router.createUrlTree([nextUrl + '/' + CD_ROUTING.TABS.GROUP], { fragment: nextFragment });

        } else if (nextTab ? nextTab === CD_ROUTING.TABS.GROUP : prevTab === CD_ROUTING.TABS.GROUP) {
            return this.router.createUrlTree([nextUrl + '/' + CD_ROUTING.TABS.DEMO], { fragment: nextFragment });
        }

        if (nextTab) {
            // the next tab is set explicitly - proceed
            return true;
        }

        if (prevTab) {
            // preserve the previous tab
            return this.router.createUrlTree([nextUrl + '/' + prevTab], { fragment: nextFragment });
        } else {
            // activate demo tab by default
            return this.router.createUrlTree([nextUrl + '/' + CD_ROUTING.TABS.DEMO], { fragment: nextFragment });
        }
    }

}
