import { ApplicationRef, enableProdMode } from '@angular/core';
import { enableDebugTools } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { bool } from '@common-ui/utils';
import { environment } from '@environments/environment';
import { AppConfig } from '@red/domain';
import { appModuleFactory } from './app/app.module';

if (environment.production) {
    enableProdMode();
}

// https://github.com/angular/angular/issues/11195#issuecomment-248020928
async function bootstrap(appConfig: AppConfig, version: { FRONTEND_APP_VERSION: string }) {
    const ruleEditorDevOnly = appConfig.RULE_EDITOR_DEV_ONLY as unknown as string | boolean;
    const config = {
        ...appConfig,
        IS_DOCUMINE: bool(appConfig.IS_DOCUMINE),
        RULE_EDITOR_DEV_ONLY:
            typeof ruleEditorDevOnly === 'string' ? ruleEditorDevOnly.toLowerCase() !== 'false' : ruleEditorDevOnly !== false,
        FRONTEND_APP_VERSION: version.FRONTEND_APP_VERSION,
    } as AppConfig;
    console.log('Started with local config: ', config);
    const appModule = appModuleFactory(config);

    const ngModuleRef = await platformBrowserDynamic().bootstrapModule(appModule, { ngZoneEventCoalescing: true });

    if (!environment.production) {
        const applicationRef = ngModuleRef.injector.get(ApplicationRef);
        const componentRef = applicationRef.components[0];
        // allows to run `ng.profiler.timeChangeDetection();`
        enableDebugTools(componentRef);
    }
}

const randomNr = Math.random().toFixed(2);
const versionPromise = fetch(`/ui/assets/version/version.json?skipCache=${randomNr}`).then(resp => resp.json());
const configPromise = fetch(`/ui/assets/config/config.json?skipCache=${randomNr}`).then(resp => resp.json());

Promise.all([configPromise, versionPromise])
    .then(([appConfig, version]) => bootstrap(appConfig, version))
    .catch(console.error);
