import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';
import { ModuleConfig } from './config/module-config';
import { _MODULE_CONFIG } from './config/token';

import { SERVICES } from './services';
import { NatsService } from './services/nats.service';

@NgModule({})
export class NatsRootModule {}

@NgModule({})
export class NatsModule {
  public static forRoot(
    config: ModuleConfig
  ): ModuleWithProviders<NatsRootModule> {
    return {
      ngModule: NatsRootModule,
      providers: [
        { provide: _MODULE_CONFIG, useValue: config },
        {
          // Preload the default language before the app starts to prevent empty/jumping content
          provide: APP_INITIALIZER,
          deps: [NatsService],
          useFactory:
            (natsService: NatsService): any =>
            (): Promise<void> => {
              return natsService.connect();
            },
          multi: true,
        },
        ...SERVICES,
      ],
    };
  }
}
