import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';

import { map, tap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

import { TranslateService as UCapTranslateService } from '@ucap-webmessenger/ui';
import { DateService as UCapDateService } from '@ucap-webmessenger/ui';

import * as AuthenticationStore from '@app/store/account/authentication';
import { LocalStorageService } from '@ucap-webmessenger/web-storage';
import { AppUserInfo, KEY_APP_USER_INFO } from '@app/types/app-user-info.type';

import { environment } from '../../../../environments/environment';

@Injectable()
export class Effects {
  postLogin$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(AuthenticationStore.postLogin),
        map(action => action.loginRes),
        tap(async loginRes => {
          const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
            KEY_APP_USER_INFO,
            environment.customConfig.appKey
          );

          this.translateService.use(appUserInfo.settings.general.locale);

          this.ucapTranslateService.use(
            appUserInfo.settings.general.hrInfoLocale
          );
          this.ucapDateService.use(appUserInfo.settings.general.timezone);
        })
      ),
    { dispatch: false }
  );

  constructor(
    private actions$: Actions,
    private translateService: TranslateService,
    private ucapTranslateService: UCapTranslateService,
    private ucapDateService: UCapDateService,
    private localStorageService: LocalStorageService
  ) {}
}
