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

import { languagesSelector } from '../selectors';
import { loadLanguagesAction, setLanguagesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ccLangs {
    ccLangs {
      id
      name
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(loadLanguagesAction.type),
    filter(() => {
      const languages = languagesSelector(state$.value);
      return !languages.length;
    }),
    switchMap(() => {
      const stream$ = gqlRequest({ query }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setLanguagesAction(data.ccLangs)));
          }

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

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