import { FactoryProvider, InjectionToken } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppSettings, defaultSettings } from '../models-legacy';
import { SettingsResolver } from './settings.resolver';

// now can be used as: constructor(@Inject(APP_SETTINGS) private settings: AppSettings)
export const APP_SETTINGS = new InjectionToken<AppSettings>('AppSettings');

export const settingsProvider: FactoryProvider = {
    provide: APP_SETTINGS,
    useFactory: resolveSettingsViaRouteDataResolver,
    deps: [ActivatedRoute],
};

function resolveSettingsViaRouteDataResolver(route: ActivatedRoute) {
    // rollup
    while (route.parent != null) route = route.parent;
    // bfs
    const stack: ActivatedRoute[] = [route];
    while (stack.length) {
        route = stack.pop();

        const settings = route.snapshot?.data[SettingsResolver.KEY];
        if (settings) {
            return settings;
        }

        route.children.forEach((c) => stack.push(c));
    }

    return defaultSettings;
}
