/**
 * Copyright (c) 2025 Broadcom. All Rights Reserved.
 * Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc.
 * and/or its subsidiaries.
 */
import { Inject, Injectable } from "@angular/core";
import { HYPER_PLUGIN_CONFIG, HyperpluginConfig } from "./lib-interfaces";
import { BehaviorSubject } from "rxjs";
import { Route, RouteConfigLoadEnd } from "@angular/router";

/**
 * Components can use this to have subscriptions automatically removed when the component is destroyed
 */
@Injectable()
export class HyperPluginRoutesStorage {
    public lazyLoadedRoutesMap: {
        [lazyLoadedPath: string]: BehaviorSubject<Route>
    } = {};

    private knownRouteSegments: string[] = [];

    constructor(
        @Inject(HYPER_PLUGIN_CONFIG) private config: HyperpluginConfig,
    ) {    
        this.config.routes.forEach((route) => {
            const extensibleRouteSegments = route.path.split("/");
            extensibleRouteSegments.forEach((segment) => {
                this.knownRouteSegments.push(segment);

                this.lazyLoadedRoutesMap[segment] = new BehaviorSubject<Route>(null);
            });
        });
    }

    checkRouterEvent(event: RouteConfigLoadEnd): void {
        if (this.knownRouteSegments.includes(event.route.path)) {
            setTimeout(() => {
                this.lazyLoadedRoutesMap[event.route.path].next(event.route);
            });
        }
    }
}