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

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

// https://github.com/angular/angular/issues/11195#issuecomment-248020928
async function bootstrap(appConfig: AppConfig, version: { FRONTEND_APP_VERSION: string }) {
    const config = { ...appConfig, FRONTEND_APP_VERSION: version.FRONTEND_APP_VERSION };

    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 versionPromise = fetch('/ui/assets/version/version.json').then(resp => resp.json());
const configPromise = fetch('/ui/assets/config/config.json').then(resp => resp.json());

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