import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';

import { JOB_STATE_CREATED, JOB_STATE_INTERRUPTED, JOB_STATE_PROCESSING } from '../../constants';

import { monitoringIdsSelector } from '../selectors';
import { getMonitoringStateAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query VideoBulkActionGetMonitoringState(
    $monitoringIds: [String],
  ) {
    videoBulkActionGetMonitoringState(
      monitoringIds: $monitoringIds,
    ) {
      entityId
      entityType
      state
      message
      type
    }
  }
`;

const DELAY = 1000;

export default (action$, state$) =>
  action$.pipe(
    ofType(getMonitoringStateAction.type),
    switchMap(() => {
      const monitoringIds = monitoringIdsSelector(state$.value);

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: {
            monitoringIds,
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap(({ data, errors }) => {
          const actions = [of(setAction({ isLoading: false }))];

          if (!errors?.length) {
            const response = data.videoBulkActionGetMonitoringState;

            const hasProcessingState =
              response.length > 0 &&
              response.some((state) =>
                [JOB_STATE_PROCESSING, JOB_STATE_CREATED, JOB_STATE_INTERRUPTED].includes(state.state),
              );

            actions.push(of(setAction({ monitoringState: response })));

            if (hasProcessingState) {
              actions.push(of(getMonitoringStateAction()).pipe(delay(DELAY)));
            }
          }

          return concat(...actions);
        }),
      );

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
