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

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

const queryGQL = `
  mutation translateLanguagesUpdate(
    $videoId: String!,
    $targetLanguages: [String],
  ) {
    translateLanguagesUpdate(
      videoId: $videoId,
      targetLanguages: $targetLanguages,
    ) {
      status
    }
  }
`;

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

      const requestParams = {
        videoId,
        targetLanguages,
        force: true,
      };

      const stream$ = gqlRequest({ query: queryGQL, variables: requestParams }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(showAutoTranslateInfoDialogAction(true)),
              of(
                checkCcFilesStateAction({
                  videoId: action.payload.videoId,
                  isActive: true,
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

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