import { Injectable, Inject } 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';
import { changeZoom, changeZoomSuccess, changeZoomFailure } from './actions';
import { UCAP_NATIVE_SERVICE, NativeService } from '@ucap-webmessenger/native';
import { Store } from '@ngrx/store';

@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.store.dispatch(changeZoom({ zoom: appUserInfo.zoom }));
        })
      ),
    { dispatch: false }
  );

  changeZoom$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(changeZoom),
        map(action => action.zoom),
        tap(zoom => {
          zoom = zoom || 100;

          const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
            KEY_APP_USER_INFO,
            environment.customConfig.appKey
          );

          this.nativeService
            .zoomTo(zoom)
            .then(f => {
              this.localStorageService.encSet<AppUserInfo>(
                KEY_APP_USER_INFO,
                {
                  ...appUserInfo,
                  zoom
                },
                environment.customConfig.appKey
              );

              this.store.dispatch(changeZoomSuccess({ zoom }));
            })
            .catch(reason => {
              this.store.dispatch(changeZoomFailure({ error: reason }));
            });
        })
      ),
    { dispatch: false }
  );

  constructor(
    private actions$: Actions,
    private store: Store<any>,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService,
    private localStorageService: LocalStorageService
  ) {}
}
