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

import { getConnectorByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query hbConnectorById(
    $id: String
  ) {
    hbConnectorById(
      id: $id
    ) {
      id
      created
      updated
      name
      status
      format 
      updatedBy
      user
      code
      numericId
      comments
      params {
        name
        label
        defaultValue
        defaultValueLabel
        required
        type
        allowedValues {
          label
          value
        }
      }  
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getConnectorByIdAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { name, code, params, comments, status, format } = data.hbConnectorById;

            actions.push(
              of(
                setFieldAction({
                  name,
                  code,
                  params,
                  comments,
                  status,
                  format,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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