import { NgModule, APP_INITIALIZER } from '@angular/core';

import axios from 'axios';

import { NativeService, NativeType } from '@ucap/native';

import { AXIOS_INSTANCE } from '@ucap/ng-core';
import { I18nService } from '@ucap/ng-i18n';
import { UCAP_NATIVE_SERVICE } from '@ucap/ng-native';

import { environment } from '@environments';

import { AppAuthenticationGuard } from './guards/app-authentication.guard';

import { AppAuthenticationService } from './services/app-authentication.service';
import { AppNativeService } from './services/app-native.service';

const GUARDS = [AppAuthenticationGuard];
const SERVICES = [AppAuthenticationService, AppNativeService];

const axiosFactory = () => {
  const i = axios.create();

  return i;
};

const appInit = (nativeService: NativeService, i18nService: I18nService) => {
  return () =>
    new Promise<void>(async (resolve, reject) => {
      switch (nativeService.type()) {
        case NativeType.Browser:
          const xhr = await import('i18next-xhr-backend').then(m => m.default);
          const languageDetector = await import(
            'i18next-browser-languagedetector'
          ).then(m => m.default);
          i18nService.use(xhr).use(languageDetector);
          break;
        // case NativeType.Electron:
        //   const nodeFs = await import('i18next-node-fs-backend').then(m => m);
        //   i18nService.use(nodeFs);
        //   break;
        default:
          break;
      }

      i18nService
        .init({
          whitelist: ['ko', 'en'],
          fallbackLng: 'ko',
          debug: true, // set debug?
          returnEmptyString: false,
          ns: [
            'common',
            'organization',
            'authentication',
            'group',
            'chat',
            'call',
            'message'
          ],
          backend: {
            loadPath: 'assets/i18n/{{lng}}/{{ns}}.json'
          }
        })
        .then(() => {
          resolve();
        })
        .catch(reason => {
          reject(reason);
        });
    });
};

@NgModule({
  imports: [],
  exports: [],
  providers: [
    {
      provide: AXIOS_INSTANCE,
      useFactory: axiosFactory,
      deps: [],
      multi: false
    },
    {
      provide: UCAP_NATIVE_SERVICE,
      useClass: environment.productConfig.nativeServiceClass,
      deps: [AXIOS_INSTANCE],
      multi: false
    },
    {
      provide: APP_INITIALIZER,
      useFactory: appInit,
      deps: [UCAP_NATIVE_SERVICE, I18nService],
      multi: true
    },
    ...GUARDS,
    ...SERVICES
  ]
})
export class AppProviderModule {}
