text: import React, { useMemo, useEffect, Fragment, createContext, useState } from 'react';
  import {
      fetchCveListBySystem,
      changeSystemCVEsParameters,
      selectSystemCve,
      expandSystemCve,
      clearSystemCvesStore,
      fetchSystemDetailsIds
  } from '../../../Store/Actions/Actions';
  import propTypes from 'prop-types';
  import messages from '../../../Messages';
  import { withRouter } from 'react-router-dom';
  import SystemCveTable from './SystemCveTable';
  import { injectIntl, IntlProvider } from 'react-intl';
  import { useDispatch, useSelector } from 'react-redux';
  import { SYSTEM_DETAILS_HEADER, CVES_ALLOWED_PARAMS } from '../../../Helpers/constants';
  import { constructFilterParameters, useUrlParams, updateRef } from '../../../Helpers/MiscHelper';
  import { createCveListBySystem } from '../../../Helpers/VulnerabilityHelper';
  import { Stack, StackItem, Text, TextContent, TextVariants } from '@patternfly/react-core';
  import DownloadReport from '../../../Helpers/DownloadReport';
  import CvePairStatusModal from '../Modals/CvePairStatusModal';
  import SystemCveTableToolbar from './SystemCveTableToolbar';
  import ErrorHandler from '../../PresentationalComponents/ErrorHandler/ErrorHandler';
  import {
      addNotification,
      clearNotifications
  } from '@redhat-cloud-services/frontend-components-notifications/redux';
  import { NotConnected } from '@redhat-cloud-services/frontend-components/NotConnected';
  
  export const CVETableContext = createContext({});
  
  export const SystemCVEs = ({ entity, intl, allowedCveActions, showHeaderLabel, setPageTitle }) => {
      const dispatch = useDispatch();
      const [StatusModal, setStatusModal] = useState(() => () => null);
      const [urlParamsAllowed, setUrlParamsAllowed] = useState(false);
      const [isFirstLoad, setIsFirstLoad] = useState(true);
  
      const systemCVEs = useSelector(
          ({ SystemCvesStore }) => SystemCvesStore.cveList
      );
      const parameters = useSelector(
          ({ SystemCvesStore }) => SystemCvesStore.parameters
      );
      const selectedCves = useSelector(
          ({ SystemCvesStore }) => SystemCvesStore.selectedCves
      );
      const expandedRows = useSelector(
          ({ SystemCvesStore }) => SystemCvesStore.expandedRows
      );
      const isAllExpanded = useSelector(
          ({ SystemCvesStore }) => SystemCvesStore.isAllExpanded
      );
  
      const [canRemediate, canEditStatus] = ['REMEDIATE', 'EDIT_STATUS'].map(action => allowedCveActions.includes(action));
      const cves = useMemo(() => createCveListBySystem(entity.id, systemCVEs), [systemCVEs, entity.id]);
      const [urlParameters, setUrlParams] = useUrlParams(CVES_ALLOWED_PARAMS);
  
      const downloadReport = format => {
          const params = { ...parameters, system: entity.id };
          DownloadReport.exec(fetchCveListBySystem, params, format, 'system-cves',  notification => dispatch(
              addNotification(notification)), () => dispatch(clearNotifications()));
      };
  
      const processError = error => {
          const { status } = error;
          const statusCode = parseInt(status);
          if (statusCode === 404 && entity.id) {
              return <NotConnected
                  titleText={intl.formatMessage(messages.notConnectedTitleText)}
                  bodyText={intl.formatMessage(messages.notConnectedBodyText)}
                  buttonText={intl.formatMessage(messages.notConnectedButtonText)}
              />;
          }
          else {
              return <ErrorHandler code={statusCode}/>;
          }
      };
  
      const apply = (filterParams = {}) => {
          const params = constructFilterParameters(filterParams);
          dispatch(changeSystemCVEsParameters(params));
      };
  
      useEffect(() => {
          if (setPageTitle) {
              document.title = `${entity.display_name}
                  - ${intl.formatMessage(messages.systemsHeader)} - ${intl.formatMessage(messages.pageTitleSuffix)}`;
          }
  
          if (isFirstLoad) {
              apply({ sort: '-public_date',  ...urlParameters });
              setIsFirstLoad(false);
          }
          else {
              dispatch(fetchCveListBySystem({ ...parameters, system: entity.id }));
              urlParamsAllowed
                  && setUrlParams({ ...parameters })
                  || setUrlParamsAllowed(true);
          }
      }, [parameters]);
  
      useEffect(() => {
          return () => {
              dispatch(clearSystemCvesStore());
          };
      }, [dispatch]);
  
      const showStatusModal = cvesList => {
          let selectedCves = Array.from(cves.data.filter(cve => cvesList.some(element => element.id === cve.id)));
          selectedCves = selectedCves.map((
              // eslint-disable-next-line camelcase
              { id, cve_status_id, status_id, status_justification: justification, cve_status_justification: cve_justification }) =>
              ({ id, cve_status_id, status_id, justification, cve_justification })); // omit properties we don't need
  
          setStatusModal(() => () =>
              (<CvePairStatusModal
                  cveList={selectedCves}
                  updateRef={() => updateRef(cves.meta, apply)}
                  inventoryList={[{ id: entity.id, display_name: entity.display_name }]}
                  type={'systemDetail'}
              />)
          );
      };
  
      const handleCveSelect = (iSelected, payload) => {
          dispatch(selectSystemCve(payload));
      };
  
      const handleCveOpen = (isOpen, cves, isAllExpanded) => {
          dispatch(expandSystemCve({ isOpen, cves, isAllExpanded }));
      };
  
      if (!systemCVEs.payload.errors) {
          return (
              <CVETableContext.Provider
                  value={{
                      cves,
                      parameters,
                      selectedCves,
                      expandedRows,
                      isAllExpanded,
                      canRemediate,
                      canEditStatus,
                      methods: {
                          apply,
                          downloadReport,
                          selectCves: handleCveSelect,
                          openCves: handleCveOpen,
                          showStatusModal,
                          fetchResource: params => fetchSystemDetailsIds({ ...params, system: entity.id })
                      }
                  }}
              >
                  <StatusModal />
  
                  <Stack hasGutter>
                      {showHeaderLabel && (
                          <StackItem>
                              <TextContent>
                                  <Text component={TextVariants.h2}>
                                      {intl.formatMessage(messages.cvesHeader)}
                                  </Text>
                              </TextContent>
                          </StackItem>
                      )}
                      <StackItem>
                          <SystemCveTableToolbar entity={entity.id} />
                      </StackItem>
                  </Stack>
  
                  <SystemCveTable
                      header={SYSTEM_DETAILS_HEADER}
                      entity={entity.id}
                  />
              </CVETableContext.Provider>
          );
      }
      else {
          return processError(systemCVEs.payload.errors);
      }
  
  };
  
  SystemCVEs.defaultProps = {
      allowedCveActions: [],
      showHeaderLabel: false,
      setPageTitle: false
  };
  
  SystemCVEs.propTypes = {
      entity: propTypes.object,
      intl: propTypes.any,
      allowedCveActions: propTypes.array,
      showHeaderLabel: propTypes.bool
  };
  
  export const ConnectedSystemCves = withRouter(
      injectIntl(SystemCVEs)
  );
  
  const TranslateSystemCves = ({ customItnlProvider, ...props }) => {
      const Wrapper = customItnlProvider ? IntlProvider : Fragment;
      return <Wrapper {...customItnlProvider && {
          locale: navigator.language.slice(0, 2),
          messages
      } } >
          <ConnectedSystemCves { ...props } />
      </Wrapper>;
  };
  
  TranslateSystemCves.propTypes = {
      customItnlProvider: propTypes.bool,
      customRouter: propTypes.bool
  };
  
  TranslateSystemCves.defaultProps = {
      customItnlProvider: false,
      customRouter: false
  };
  
  export default TranslateSystemCves;
  