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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { getSlidesAction, runPdfMonitoringAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query AiWorkbenchPdfMonitoringSlidesQuery($videoId: String!) {
    aiWorkbenchPdfMonitoringSlides(videoId: $videoId) {
      jobs {
        videoId
        state
        progress
      }
    }
  }
`;

const getResponse = ({ data: { aiWorkbenchPdfMonitoringSlides } }) => aiWorkbenchPdfMonitoringSlides?.jobs[0];

const MONITORING_DELAY = 2000;

const MONITORING_STATUS = {
  STARTED: 'STARTED',
  PROCESSING: 'PROCESSING',
  DONE: 'DONE',
  ERROR: 'ERROR',
  FAILED: 'FAILED',
};

export default (action$, state$) =>
  action$.pipe(
    ofType(runPdfMonitoringAction.type),
    debounceTime(MONITORING_DELAY),
    switchMap(() => {
      const video = selectedVideoSelector(state$.value);

      if (!video?.uid) {
        return EMPTY;
      }

      const stream$ = gqlRequest({
        query,
        variables: { videoId: video.uid },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const job = getResponse(response);

            switch (job?.state) {
              case MONITORING_STATUS.DONE: {
                return concat(
                  of(getSlidesAction({ isPdfMonitoringUpdate: true })),
                  of(setAction({ isPdfFileReadyToDownload: true })),
                );
              }
              case MONITORING_STATUS.STARTED:
              case MONITORING_STATUS.PROCESSING: {
                return concat(of(setAction({ isPdfFileReadyToDownload: false })), of(runPdfMonitoringAction()));
              }
              case MONITORING_STATUS.ERROR:
              case MONITORING_STATUS.FAILED: {
                return concat(
                  of(
                    showNotificationAction({
                      type: TYPE_ERROR,
                      message: 'Pdf generation is failed',
                    }),
                  ),
                );
              }
              default: {
                return EMPTY;
              }
            }
          }

          return EMPTY;
        }),
      );

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