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

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { selectedTranslateFileSelector } from '../selectors';
import { getSubtitleAction, getTranslationFilesAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query AiWorkbenchGetTranslationFilesQuery(
    $videoId: String!,
  ) {
    aiWorkbenchGetTranslationFiles(
      videoId: $videoId,
    ) {
      data {
        file
        lang
        langName
        sizeInBytes
        source
        version
        state
        operationId  
      }
    }
    aiWorkbenchGetTranslationCcSegments(
      videoId: $videoId
    ) {
      data {
        uid
        transcript
        provider
        speakerId
        startTime
        endTime
        tokens {
          startTime
          endTime
          word
          kind
          confidence
        }
      }
    }
     aiWorkbenchGetTranslationCcLanguages {
      id
      name
    }
    aiWorkbenchGetTranslationTranslateLanguages {
      id
      name
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getTranslationFilesAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const selectedTranslateFile = selectedTranslateFileSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const {
            aiWorkbenchGetTranslationFiles,
            aiWorkbenchGetTranslationCcSegments,
            aiWorkbenchGetTranslationCcLanguages,
            aiWorkbenchGetTranslationTranslateLanguages,
          } = data;

          const translationFiles = aiWorkbenchGetTranslationFiles?.data ?? [];
          const selectedTranslateFileByDefault =
            selectedTranslateFile ||
            translationFiles.find((file) => file.lang === video.lang[0])?.lang ||
            translationFiles[0]?.lang;

          const ccSegments = aiWorkbenchGetTranslationCcSegments?.data;

          if (!errors?.length) {
            const state = {
              translationFiles,
              ccSegments,
              selectedTranslateFile: selectedTranslateFileByDefault ?? null,
              languages: aiWorkbenchGetTranslationCcLanguages,
              translateLanguages: aiWorkbenchGetTranslationTranslateLanguages,
              isLoading: selectedTranslateFileByDefault,
            };

            if (action.payload?.shouldNotRequestSubtitle) {
              state.isLoading = false;
            } else {
              state.subtitle = null;
            }

            actions.push(of(setAction(state)));

            if (selectedTranslateFileByDefault && !action.payload?.shouldNotRequestSubtitle) {
              actions.push(of(getSubtitleAction(selectedTranslateFileByDefault)));
            }
          }

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

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
