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

import { HB_CONNECTOR_STATUSES, HB_FORMATS } from '../../constants';

import * as selectors from '../selectors';
import { getConnectorsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query hbConnectorsSearch(
    $from: Int,
    $size: Int,
    $query: String,
    $status: String
    $format: String
  ) {
    hbConnectorsSearch(
      from: $from,
      size: $size,
      query: $query,
      status: $status
      format: $format
    ) {
      totalCount
      data {
        id
        created
        updated
        name
        status
        format
        updatedBy
        user
        code
        numericId
        comments
        params {
          name
          label
          defaultValue
          defaultValueLabel
          required
          type
          allowedValues {
            label
            value
          }
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getConnectorsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap(() => {
      const state = state$.value;

      const search = selectors.searchSelector(state);
      const page = selectors.pageSelector(state);
      const rowsPerPage = selectors.rowsPerPageSelector(state);
      const filterStatus = selectors.filterStatusSelector(state);
      const filterFormat = selectors.filterFormatSelector(state);

      let requestParams = {};

      if (search?.length) {
        requestParams = {
          ...requestParams,
          query: search,
        };
      }
      if (filterStatus !== HB_CONNECTOR_STATUSES.allStatuses) {
        requestParams = {
          ...requestParams,
          status: filterStatus,
        };
      }
      if (filterFormat !== HB_FORMATS[0].value) {
        requestParams = {
          ...requestParams,
          format: filterFormat,
        };
      }
      const stream$ = gqlRequest({
        query,
        variables: {
          size: rowsPerPage || 10,
          from: (page || 0) * (rowsPerPage || 10),
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { data: connectors, totalCount } = data.hbConnectorsSearch;

            actions.push(
              of(
                setFieldAction({
                  totalCount,
                  connectors,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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