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

import { HttpClientModule } from '@angular/common/http';
import { APP_INITIALIZER, InjectionToken, NgModule, Optional, SkipSelf } from '@angular/core';
import { MAT_DIALOG_DEFAULT_OPTIONS, MatDialogConfig } from '@angular/material/dialog';
import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltipDefaultOptions } from '@angular/material/tooltip';
import { throwIfAlreadyLoaded } from '../module-import-guard';
import { CoreConfig } from './core-config';
import { CoreConfigurationLoaderService } from './core-configuration-loader.service';

export const CORE_CONFIG_URL = new InjectionToken<string>('CORE_CONFIG_URL');

export function coreConfigInitializer(
  coreConfigLoaderService: CoreConfigurationLoaderService,
  coreConfigUrl: string
): () => Promise<CoreConfig> {
  if (!coreConfigUrl || coreConfigUrl.length === 0) {
    return function () {
      return Promise.resolve(new CoreConfig());
    };
  }
  const t = coreConfigLoaderService;
  return function () {
    return t.load(coreConfigUrl);
  };
}

export const dialogDefaultOptions: MatDialogConfig<any> = {
  ...new MatDialogConfig(),
  ...{
    width: 'auto',
    height: 'auto',
  },
};

export const tooltipDefaultOptions: MatTooltipDefaultOptions = {
  hideDelay: 777,
  showDelay: 777,
  touchendHideDelay: 1500,
};

@NgModule({
  imports: [HttpClientModule],
  providers: [
    CoreConfigurationLoaderService,
    {
      provide: APP_INITIALIZER,
      useFactory: coreConfigInitializer,
      // useFactory: (coreConfigService: CoreConfigurationService) =>  coreConfigInitializer(coreConfigService) ,
      deps: [CoreConfigurationLoaderService, CORE_CONFIG_URL],
      multi: true,
    },
    {
      provide: MAT_DIALOG_DEFAULT_OPTIONS,
      useValue: dialogDefaultOptions,
    },
    {
      provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
      useValue: tooltipDefaultOptions,
    },
  ],
})
export class CoreConfigurationModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreConfigurationModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreConfigurationModule');
  }
}
