import {
  NgModule,
  Inject,
  APP_BOOTSTRAP_LISTENER,
  InjectionToken, Type,
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppCommonModule,AppCommonServiceModule,AuthConfigFactory,FM_COMMON_STARTPAGE } from '@farmmaps/common';

import {AppRootComponent} from './app.component';

import {StoreModule, ActionReducer,MetaReducer} from '@ngrx/store';
import {EffectsModule, EffectSources} from '@ngrx/effects';
import { StoreRouterConnectingModule,routerReducer} from '@ngrx/router-store';

import {AppRoutingModule} from './app-routing.module';
import { LogoComponent } from './logo/logo.component';
import { MenuComponent } from './menu/menu.component';
import {RegisterDeviceComponent} from './registerdevice/registerdevice.component';
import { SecureOAuthStorage} from '@farmmaps/common';
import { OAuthStorage } from 'angular-oauth2-oidc';
import {Id4AuthconfigFactory} from './id4AuthconfigFactory';
import { TestComponent } from './test/test.component';
import { LandingpageComponent } from './landingpage/landingpage.component';

export const BOOTSTRAP_EFFECTS = new InjectionToken('Bootstrap Effects');

export function bootstrapEffects(effects: Type<any>[], sources: EffectSources) {
  return () => {
    effects.forEach(effect => sources.addEffects(effect));
  };
}

export function createInstances(...instances: any[]) {
  return instances;
}

export function provideBootstrapEffects(effects: Type<any>[]) {
  return [
    effects,
    {provide: BOOTSTRAP_EFFECTS, deps: effects, useFactory: createInstances},
    {
      provide: APP_BOOTSTRAP_LISTENER,
      multi: true,
      useFactory: bootstrapEffects,
      deps: [[new Inject(BOOTSTRAP_EFFECTS)], EffectSources],
    },
  ];
}

// console.log all actions
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
  return function(state, action) {
    //console.debug('-- State', state);
    //console.debug('-- Action', action);
 
    return reducer(state, action);
  };
}

export const metaReducers: MetaReducer<any>[] = [debug];

@NgModule({
  declarations: [
    AppRootComponent,
    LogoComponent,
    MenuComponent,
    RegisterDeviceComponent,
    TestComponent,
    LandingpageComponent
  ],
  imports: [
    AppRoutingModule,
    AppCommonModule,
    AppCommonServiceModule.forRoot(),
    BrowserModule,
    StoreModule.forRoot({router:routerReducer},{metaReducers,runtimeChecks: { // TODO fix this should all be true
			strictStateImmutability: false,
			strictActionImmutability: false,
			strictStateSerializability: false,
			strictActionSerializability: false
    }}),
    StoreRouterConnectingModule.forRoot({stateKey:"router"}),
    EffectsModule.forRoot([]),   
  ],
  providers: [
    AuthConfigFactory,    
    {
       provide:AuthConfigFactory,
       useClass:Id4AuthconfigFactory
    },
    {
       provide: FM_COMMON_STARTPAGE,
       useValue: '/map'
    }
   ],
  bootstrap: [AppRootComponent]
})
export class AppModule { }
