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

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

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

import { NGXLogger } from 'ngx-logger';
import * as SyncStore from '@app/store/messenger/sync';
import {
  bulkInfo,
  bulkInfoSuccess,
  bulkInfoFailure,
  statusNotification
} from './actions';
import { tap, switchMap, map, catchError } from 'rxjs/operators';
import {
  StatusProtocolService,
  SSVC_TYPE_STATUS_BULK_INFO_DATA,
  SSVC_TYPE_STATUS_BULK_INFO_RES,
  BulkInfoData,
  StatusBulkInfo
} from '@ucap-webmessenger/protocol-status';
import { of } from 'rxjs';

@Injectable()
export class Effects {
  buddy2SuccessPostBulk$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SyncStore.buddy2Success),
      map(params => {
        const userSeqList: number[] = [];
        for (const buddy of params.buddyList) {
          userSeqList.push(buddy.seq);
        }

        return bulkInfo({ divCd: 'bulk', userSeqs: userSeqList });
      })
    )
  );

  bulkInfo$ = createEffect(
    () => {
      let statusBulkInfoList: StatusBulkInfo[];

      return this.actions$.pipe(
        ofType(bulkInfo),
        tap(() => {
          statusBulkInfoList = [];
        }),
        switchMap(req => {
          return this.statusProtocolService.bulkInfo(req).pipe(
            map(res => {
              switch (res.SSVC_TYPE) {
                case SSVC_TYPE_STATUS_BULK_INFO_DATA:
                  statusBulkInfoList.push(
                    ...(res as BulkInfoData).statusBulkInfos
                  );
                  break;
                case SSVC_TYPE_STATUS_BULK_INFO_RES:
                  this.store.dispatch(
                    bulkInfoSuccess({
                      statusBulkInfoList
                    })
                  );
                  break;
              }
            }),
            catchError(error => of(bulkInfoFailure({ error })))
          );
        })
      );
    },
    { dispatch: false }
  );

  // statusNotification$ = createEffect(
  //   () => {
  //     return this.actions$.pipe(
  //       ofType(statusNotification),
  //       map(action => action.noti),
  //       tap(noti => {})
  //     );
  //   },
  //   { dispatch: false }
  // );

  constructor(
    private actions$: Actions,
    private store: Store<any>,
    private statusProtocolService: StatusProtocolService,
    private logger: NGXLogger
  ) {}
}
