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

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

const queryGQL = `
  query AiWorkbenchGetTranslationSubtitleQuery(
    $videoId: String!,
    $lang: String!,
  ) {
    aiWorkbenchGetTranslationSubtitle(
      videoId: $videoId,
      lang: $lang,
    ) {
      data {
        uid
        startTime
        endTime
        text
        tokens {
          segmentId
          startTime
          endTime
          value
          originalValue
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getSubtitleAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const lang = action.payload;

      if (!video?.uid) {
        return concat(of(setAction({ selectedTranslateFile: null })));
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          lang,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const response = data.aiWorkbenchGetTranslationSubtitle;
          const subtitle = response?.data ?? [];

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  subtitle,
                  isLoading: false,
                }),
              ),
            );
          }

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

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