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

import { getLiveEventsAction, setLiveEventsAction, setTotalEventsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

const queryGQL = `
  query liveEventsSearch($search: String, $playerId: Int, $eventFilter: String, $publisherIds: [Int], $page: Int, $pageSize: Int, $sortBy: String, $sortOrder: String, $status: String) {
    liveEventsSearch(search: $search, playerId: $playerId, eventFilter: $eventFilter, publisherIds: $publisherIds, page: $page, pageSize: $pageSize, sortBy: $sortBy, sortOrder: $sortOrder, status: $status){
      total
      page
      pageSize
      results {
        id
        status
        name
        description
        updatedAt
        updatedBy
        timezone
        streamId
        indicationText
        indicationColor
        playerId
        guid
        preEventText
        postEventText
        countdown
        transitionText
        preEventType
        preEventId
        postEventType
        postEventId
        player {
          name,
          id,
          publisher {
            name,
            id
          }
        }
        liveEventSchedules {
          title,
          startTime,
          endTime,
          durationIn
        }
        aspectRatio
        status
        recurrent,
        recurrentEndDate,
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getLiveEventsAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap((action) => {
      const { publisherId, ...variables } = action.payload;

      if (publisherId) {
        variables.publisherIds = [publisherId];
      }

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

          if (!errors.length) {
            const { total, results } = data.liveEventsSearch;

            actions.push(of(setTotalEventsAction(total)), of(setLiveEventsAction(results)));
          }
          return concat(...actions);
        }),
      );

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