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

import { CC_FILES_STATUS } from '@/modules/@common/ccFiles/constants';

import { checkCcFilesStateAction, getCcFilesAction, setCcFilesAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetCcFilesByVideoId(
    $videoId: String!
  ) {
    getCcFilesByVideoId(
      videoId: $videoId
    ) {
      data {
        file
        lang
        langName
        sizeInBytes
        source
        version
        state
        operationId  
      }
    }  
  }
`;

const getResponse = ({ data: { getCcFilesByVideoId } }) => getCcFilesByVideoId.data;

const MONITORING_DELAY = 5000;

export default (action$) =>
  action$.pipe(
    ofType(getCcFilesAction.type),
    switchMap((action) => {
      const variables = { videoId: action.payload };

      const stream$ = gqlRequest({ query, variables }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);
            const hasFilesInProgressState = data.some((ccFile) => ccFile.state === CC_FILES_STATUS.processing);
            const actions = [of(setCcFilesAction(data))];

            if (hasFilesInProgressState) {
              actions.push(
                of(
                  checkCcFilesStateAction({
                    videoId: action.payload,
                    isActive: true,
                  }),
                ).pipe(delay(MONITORING_DELAY)),
              );
            }

            return concat(...actions);
          }

          return EMPTY;
        }),
      );

      return concat(stream$);
    }),
  );
