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

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

const query = `
  mutation AddCcFilesToVideo(
    $videoId: String!
    $file: String!
    $lang: String!
  ) {
    addCcFilesToVideo(
      videoId: $videoId
      file: $file
      lang: $lang
    ) {
      file
      lang
      langName
      sizeInBytes
      source
      version
      state
      operationId
    }  
  }
`;

const getResponse = ({ data: { addCcFilesToVideo } }) => addCcFilesToVideo;

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

      const variables = {
        videoId: action.payload.videoId,
        file: action.payload.file,
        lang: action.payload.lang,
      };

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

            // replace opened file from response
            const currentCcFiles = ccFiles[runContext];
            const ccFilesToUpdate = currentCcFiles.map((ccFile) => {
              if (ccFile.file === action.payload.file) {
                return data;
              }

              return ccFile;
            });

            return of(setCcFilesAction(ccFilesToUpdate));
          }

          return EMPTY;
        }),
      );

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