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

import { ROWS_PER_PAGE_DEFAULT_FILTER } from '@/modules/players/Players/constants';

import { getPlayerEditorialPlaylistsOptionsAction, setAction, setPlayerIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getPlayerEditorialPlaylists(
    $publisherId: Int
    $searchText: String
    $pageSize: Int
  ) {
    getPlayerEditorialPlaylists(
      publisherId: $publisherId
      searchText: $searchText
      pageSize: $pageSize
    ) {
    records{
      id
      title
      clips{
        title
        image
        mediaid
        file
        files {
           width
           height
           file
        }
        images {
           width
           height
           file
        }
        hlsFile {
           file  
        }
      }
      }
      recordsTotal
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlayerEditorialPlaylistsOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search?.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actions = [];
      const stream$ = gqlRequest({
        query,
        variables: {
          publisherId: action.payload.publisherId,
          searchText: action.payload.searchText ?? '',
          pageSize: ROWS_PER_PAGE_DEFAULT_FILTER,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  playerEditorialPlaylistsOptions: response.data.getPlayerEditorialPlaylists?.records,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
