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

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

import { checkCcFilesStateAction, getCcFilesAction } from '../../slices';
import { checkCcFileStateMonitoringIsActiveSelector } from '@/modules/@common/ccFiles/redux/selectors';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

const MONITORING_DELAY = 5000;

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

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

      const checkCcFileStateMonitoringIsActive = checkCcFileStateMonitoringIsActiveSelector(state$.value);

      if (!checkCcFileStateMonitoringIsActive) {
        return EMPTY;
      }

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

            switch (job?.state) {
              case MONITORING_STATUS.DONE: {
                return concat(of(checkCcFilesStateAction({ videoId, isActive: false })));
              }
              case MONITORING_STATUS.STARTED:
              case MONITORING_STATUS.PROCESSING: {
                return concat(of(checkCcFilesStateAction({ videoId, isActive: true })).pipe(delay(MONITORING_DELAY)));
              }
              case MONITORING_STATUS.ERROR:
              case MONITORING_STATUS.FAILED: {
                return concat(
                  of(checkCcFilesStateAction({ videoId, isActive: false })),
                  of(
                    showNotificationAction({
                      type: TYPE_ERROR,
                      message: 'CC translate is failed',
                    }),
                  ),
                );
              }
              default: {
                return EMPTY;
              }
            }
          }

          return EMPTY;
        }),
      );

      return concat(of(getCcFilesAction(videoId)), stream$);
    }),
  );
