import { Case, Switch } from '@chipp972/react-case-when';
import React from 'react';
import { useSelector } from 'react-redux';
import { getResponse, isRequestFailed, isRequestSuccessful } from '../redux-ajax.selector';

type Props = {
  requestIds: string[];
  loading: React.ReactNode;
  failure: React.ReactNode;
  success: React.ReactNode;
  validateRequests?: (param: any) => boolean;
};

export const ReduxAjaxContainer: React.FC<Props> = ({ requestIds, loading, failure, validateRequests, success }) => {
  const responses = useSelector((state) =>
    requestIds.reduce(
      (result, requestId) => ({
        ...result,
        [requestId]: getResponse(requestId)(state)
      }),
      {}
    )
  );
  const areAllRequestsSuccessful = useSelector((state) =>
    requestIds.every((requestId) => isRequestSuccessful(requestId)(state))
  );
  const hasSomeRequestFailed = useSelector((state) =>
    requestIds.some((requestId) => isRequestFailed(requestId)(state))
  );

  const isValid = validateRequests && areAllRequestsSuccessful ? validateRequests(responses) : true;

  return (
    <Switch>
      <Case when={hasSomeRequestFailed || !isValid}>{failure}</Case>
      <Case when={areAllRequestsSuccessful && isValid}>{success}</Case>
      <Case>{loading}</Case>
    </Switch>
  );
};
