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

import { ccFilesSelector, runContextSelector } from '../../selectors';
import { deleteCcFileAction, setCcFilesAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation DeleteCcFilesFromVideo(
    $videoId: String!
    $file: String
    $lang: String
    $langName: String
    $sizeInBytes: Int
    $source: String
    $version: String
    $state: String
    $operationId: String
    $shouldDeleteAll: Boolean
  ) {
    deleteCcFilesFromVideo(
      videoId: $videoId
      file: $file
      lang: $lang
      langName: $langName
      sizeInBytes: $sizeInBytes
      source: $source
      version: $version
      state: $state
      operationId: $operationId
      shouldDeleteAll: $shouldDeleteAll
    ) {
      complete
    }  
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(deleteCcFileAction.type),
    switchMap((action) => {
      const ccFiles = ccFilesSelector(state$.value);
      const runContext = runContextSelector(state$.value);

      const shouldDeleteAll = !(action.payload?.file && action.payload?.lang);

      const variables = { ...action.payload };

      if (shouldDeleteAll) {
        variables.shouldDeleteAll = true;
      }

      const stream$ = gqlRequest({ query, variables }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            // replace opened file from response
            const currentCcFiles = ccFiles[runContext];
            const ccFilesToUpdate = shouldDeleteAll
              ? []
              : currentCcFiles.filter((ccFile) => ccFile.file !== action.payload.file);

            return of(setCcFilesAction(ccFilesToUpdate));
          }

          return EMPTY;
        }),
      );

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