import { Injectable, Inject } from '@angular/core';

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

import { Store } from '@ngrx/store';

import { NGXLogger } from 'ngx-logger';
import { catchError, exhaustMap, map, tap, switchMap } from 'rxjs/operators';
import {
  selectedMassDetail,
  massTalkDownload,
  massTalkDownloadFailure,
  massTalkDownloadSuccess,
  clearSelectedRoom
} from './actions';
import { of } from 'rxjs';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { StatusCode } from '@ucap-webmessenger/api';
import { CommonApiService } from '@ucap-webmessenger/api-common';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';
import { EnvironmentsInfo, KEY_ENVIRONMENTS_INFO } from '@app/types';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import {
  DialogService,
  AlertDialogComponent,
  AlertDialogData
} from '@ucap-webmessenger/ui';
import { initialState } from '../event';
import {
  MassDetailComponent,
  MassDetailDialogData
} from '@app/layouts/messenger/dialogs/chat/mass-detail.component';

@Injectable()
export class Effects {
  selectedMassDetail$ = createEffect(() =>
    this.actions$.pipe(
      ofType(selectedMassDetail),
      map(action => {
        const loginResInfo: LoginResponse = this.sessionStorageService.get<
          LoginResponse
        >(KEY_LOGIN_RES_INFO);

        const environmentsInfo = this.sessionStorageService.get<
          EnvironmentsInfo
        >(KEY_ENVIRONMENTS_INFO);

        return massTalkDownload({
          userSeq: loginResInfo.userSeq,
          deviceType: environmentsInfo.deviceType,
          eventMassSeq: Number(action.massEventSeq),
          token: loginResInfo.tokenString
        });
      })
    )
  );

  massTalkDownload$ = createEffect(
    () => {
      return this.actions$.pipe(
        ofType(massTalkDownload),
        map(action => action),
        exhaustMap(req => {
          return this.commonApiService.massTalkDownload(req).pipe(
            map(res => {
              if (res.statusCode === StatusCode.Success) {
                this.store.dispatch(massTalkDownloadSuccess(res));

                const result = this.dialogService.open<
                  MassDetailComponent,
                  MassDetailDialogData
                >(MassDetailComponent, {
                  disableClose: false,
                  width: '550px',
                  data: {
                    title: 'Detail View',
                    contents: res.content
                  }
                });
              } else {
                this.store.dispatch(massTalkDownloadFailure({ error: res }));
              }
            }),
            catchError(error => of(massTalkDownloadFailure({ error })))
          );
        })
      );
    },
    { dispatch: false }
  );

  constructor(
    private actions$: Actions,
    private commonApiService: CommonApiService,
    private sessionStorageService: SessionStorageService,
    private dialogService: DialogService,
    private store: Store<any>,
    private logger: NGXLogger
  ) {}
}
