/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { OverlayModule } from '@angular/cdk/overlay';
import { PortalModule } from '@angular/cdk/portal';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions } from '@angular/material/core';
import { MatFormFieldDefaultOptions, MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';
import { MatIconRegistry } from '@angular/material/icon';
import { MAT_SELECT_CONFIG } from '@angular/material/select';
import { BciComponentModule } from './component.module';
import { CORE_CONFIG_URL, CoreConfigurationModule } from './core-configuration/core-configuration.module';
import { ENVIRONMENT_PROD } from './environment-prod.token';
import { BCI_IMPRINT_INTL_PROVIDER } from './imprint/imprint-intl';
import { BCI_MESSAGES_INTL_PROVIDER } from './messages/messages-intl';
import { throwIfAlreadyLoaded } from './module-import-guard';

export interface ICoreModuleConfig {
  prod_environment?: boolean;
  core_config_url?: string;
}

export const DefaultCoreModuleConfig: ICoreModuleConfig = {
  prod_environment: false,
  core_config_url: undefined,
};

const globalRippleConfig: RippleGlobalOptions = {
  disabled: true,
  animation: {
    enterDuration: 0,
    exitDuration: 0,
  },
};

@NgModule({
  imports: [
    CommonModule,
    // TODO: needed?
    FormsModule,
    HttpClientModule,
    CoreConfigurationModule,
    /* CDK */
    OverlayModule,
    PortalModule,
    BciComponentModule,
  ],
  declarations: [],
  exports: [HttpClientModule],
  providers: [
    { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: <MatFormFieldDefaultOptions>{ floatLabel: 'always' } },
    { provide: MAT_RIPPLE_GLOBAL_OPTIONS, useValue: globalRippleConfig },
    { provide: MAT_SELECT_CONFIG, useValue: { disableOptionCentering: true } },
    BCI_IMPRINT_INTL_PROVIDER,
    BCI_MESSAGES_INTL_PROVIDER,
  ],
})
export class BciCoreModule {
  constructor(@Optional() @SkipSelf() parentModule: BciCoreModule, private iconRegistry: MatIconRegistry) {
    throwIfAlreadyLoaded(parentModule, 'BciCoreModule');

    iconRegistry.registerFontClassAlias('bosch', 'Bosch-Ic').setDefaultFontSetClass('Bosch-Ic');
  }

  static forRoot(config: ICoreModuleConfig): ModuleWithProviders<BciCoreModule> {
    return {
      ngModule: BciCoreModule,
      providers: [
        {
          provide: ENVIRONMENT_PROD,
          useValue: config.prod_environment || DefaultCoreModuleConfig.prod_environment,
        },
        {
          provide: CORE_CONFIG_URL,
          useValue: config.core_config_url,
        },
      ],
    };
  }
}
