text: import * as AppActions from '../../AppActions';
  
  import { Button, Card, TextContent } from '@patternfly/react-core/dist/esm/components';
  import { Flex, FlexItem } from '@patternfly/react-core/dist/esm/layouts';
  import React, { useEffect } from 'react';
  import { Table, TableBody, TableHeader, TableText, fitContent } from '@patternfly/react-table';
  import { TemplateCard, TemplateCardBody, TemplateCardHeader } from '../../PresentationalComponents/Template/TemplateCard';
  import { useDispatch, useSelector } from 'react-redux';
  
  import { ExpandableCardTemplate } from '../../PresentationalComponents/Template/ExpandableCardTemplate';
  import FailState from '../../PresentationalComponents/FailState/FailState';
  import Loading from '../../PresentationalComponents/Loading/Loading';
  import { PieChart } from '../../ChartTemplates/PieChart/PieChartTemplate';
  import { UI_BASE } from '../../AppConstants';
  import messages from '../../Messages';
  import { useIntl } from 'react-intl';
  
  const VulnerabilityCard = () => {
      const intl = useIntl();
      const columns = [{ title: 'CVSS score', transforms: [fitContent] }, { title: 'CVE totals', transforms: [fitContent] }];
      const pieChartPadding = { bottom: 0, left: 0, right: 0, top: 0 };
      let chartData = [];
      let rows = [];
      let legendLink = [];
  
      const dispatch = useDispatch();
      const vulnerabilities = useSelector(({ DashboardStore }) => DashboardStore.vulnerabilities);
      const vulnerabilitiesFetchStatus = useSelector(({ DashboardStore }) => DashboardStore.vulnerabilitiesFetchStatus);
      const selectedTags = useSelector(({ DashboardStore }) => DashboardStore.selectedTags);
      const workloads = useSelector(({ DashboardStore }) => DashboardStore.workloads);
      const SID = useSelector(({ DashboardStore }) => DashboardStore.SID);
  
      useEffect(() => {
          const options = {
              ...workloads?.SAP?.isSelected && { sap_system: true },
              ...SID?.length > 0 && { sap_sids: SID },
              ...selectedTags?.length > 0 && { tags: selectedTags }
          };
          const fetchVulnerabilities = options => dispatch(AppActions.fetchVulnerabilities(options));
  
          fetchVulnerabilities(options);
      }, [workloads, SID, selectedTags, dispatch]);
  
      if (vulnerabilitiesFetchStatus === 'fulfilled') {
          let { cves_by_severity: bySeverity } = vulnerabilities;
  
          chartData = [
              {
                  x: 'CVSS 8.0 - 10',
                  from: 8.0,
                  to: 10.0,
                  y: bySeverity['8to10'].count,
                  fill: '#a30000'
              },
              {
                  x: 'CVSS 4.0 - 7.9',
                  from: 4.0,
                  to: 7.9,
                  y: bySeverity['4to7.9'].count,
                  fill: '#ec7a08'
              },
              {
                  x: 'CVSS 0.0 - 3.9',
                  from: 0.0,
                  to: 3.9,
                  y: bySeverity['0to3.9'].count,
                  fill: '#f0ab00'
              }
          ];
  
          legendLink = chartData.map((data) => `${UI_BASE}/vulnerability/cves?cvss_from=${data.from}&cvss_to=${data.to}`);
  
          rows = [[{
              title: <TableText wrapModifier='nowrap' className='ins-c-legend__dot'
                  style={{ '--ins-c-legend__dot--BackgroundColor': '#a30000' }}>
                  <a href={legendLink[0]}>8.0 - 10</a>
              </TableText>
          }, {
              title: <a href={legendLink[0]} className='pf-u-text-align-center'>{bySeverity['8to10'].count}</a>,
              props: { textCenter: true }
          }
          ], [{
              title: <TableText wrapModifier='nowrap' className='ins-c-legend__dot'
                  style={{ '--ins-c-legend__dot--BackgroundColor': '#ec7a08' }}>
                  <a href={legendLink[1]} className='pf-u-text-align-center'>4.0 - 7.9</a>
              </TableText>
          }, {
              title: <a href={legendLink[1]} className='pf-u-text-align-center'>{bySeverity['4to7.9'].count}</a>,
              props: { textCenter: true }
          }
          ], [{
              title: <TableText wrapModifier='nowrap' className='ins-c-legend__dot'
                  style={{ '--ins-c-legend__dot--BackgroundColor': '#f0ab00' }}>
                  <a href={legendLink[2]}>0.0 - 3.9</a>
              </TableText>
          }, {
              title: <a href={legendLink[2]}>{bySeverity['0to3.9'].count}</a>,
              props: { textCenter: true }
          }]];
  
      }
  
      if (vulnerabilitiesFetchStatus === 'rejected') {
          return <TemplateCard isFilled={false} className='ins-c-card__vulnerability' data-ouia-safe>
              <TemplateCardHeader title={intl.formatMessage(messages.vulnerabilitiesTitle)} />
              <TemplateCardBody><FailState appName='Vulnerability' /></TemplateCardBody>
          </TemplateCard>;
      }
  
      return <Card component='div' className='ins-c-dashboard-card-parent' data-ouia-safe={vulnerabilitiesFetchStatus !== 'pending'}>
          <ExpandableCardTemplate
              appName='Vulnerabilities'
              className='ins-m-toggle-right-on-md ins-m-short-header'
              data-ouia-safe={vulnerabilitiesFetchStatus !== 'pending'}
              title={intl.formatMessage(messages.vulnerabilitiesTitle)}
              isExpanded={JSON.parse(localStorage.getItem('dashboard_expanded_vulnerability1') || 'true')}
              isExpandedCallback={isExpanded => localStorage.setItem('dashboard_expanded_vulnerability1', isExpanded)}
              body={
                  vulnerabilitiesFetchStatus !== 'fulfilled' ? <Loading /> :
                      <TemplateCardBody className='ins-c-custom-policies__card-body'>
                          <Flex
                              direction={{ default: 'column' }}
                              spaceItems={{ default: 'spaceItemsLg' }}>
                              <TextContent>
                                  <p className='pf-u-font-size-sm'>
                                      {intl.formatMessage(messages.vulnerabilityMessage)}
                                  </p>
                              </TextContent>
                              <Flex
                                  direction={{ default: 'column' }}
                                  spaceItems={{ default: 'spaceItemsLg' }}
                                  alignItems={{ default: 'alignItemsCenter' }}
                                  justifyContent={{ default: 'justifyContentCenter' }}>
                                  <Flex
                                      direction={{ default: 'column' }}
                                      spaceItems={{ default: 'spaceItemsNone' }}>
                                      <a className='pf-u-font-size-2xl pf-u-text-align-center pf-u-color-100'
                                          href={`${UI_BASE}/vulnerability/`} rel='noreferrer'>
                                          {intl.formatMessage(messages.vulnerabilitiesTotalItems, { total: vulnerabilities.rules_total
                                              || vulnerabilities.rules_cves_total })}
                                      </a>
                                      <TextContent
                                          className='ins-c-width-limiter pf-u-text-align-center'
                                          style={{ '--ins-c-width-limiter--MaxWidth': '24ch' }}>
                                          <p className='pf-u-font-size-sm'>
                                              {intl.formatMessage(messages.cvesImpactingOneOrMoreSystems, { cves: vulnerabilities.rules_total
                                                  || vulnerabilities.rules_cves_total })}
                                          </p>
                                      </TextContent>
                                  </Flex>
                                  <Button component='a' href={`${UI_BASE}/vulnerability/cves?affecting=true,false&rule_presence=true`} rel='noreferrer'
                                      variant='secondary' isSmall>
                                      {intl.formatMessage(messages.vulnerabilityCardCTAText)}
                                  </Button>
                              </Flex>
                          </Flex>
                      </TemplateCardBody>
              }/>
          <ExpandableCardTemplate
              appName='CVESbyCVSS'
              className='ins-m-toggle-right-on-md'
              data-ouia-safe={vulnerabilitiesFetchStatus !== 'pending'}
              title={intl.formatMessage(messages.cveByCvssScoreTitle)}
              isExpanded={JSON.parse(localStorage.getItem('dashboard_expanded_vulnerability2') || 'true')}
              isExpandedCallback={isExpanded => localStorage.setItem('dashboard_expanded_vulnerability2', isExpanded)}
              hasDivider
              body={vulnerabilitiesFetchStatus !== 'fulfilled' ? <Loading /> :
                  <TemplateCardBody className='ins-c-custom-policies__card-body pf-u-pt-sm'>
                      <Flex alignItems={{ default: 'alignItemsCenter' }}>
                          <FlexItem>
                              <PieChart
                                  ariaDesc={intl.formatMessage(messages.cvesImpactingSystems,
                                      { cves: vulnerabilities.cves_total })}
                                  ariaTitle='Vulnerabilities chart'
                                  constrainToVisibleArea={true}
                                  data={chartData}
                                  padding={pieChartPadding}
                                  height={100}
                                  width={100}
                                  colorScale={['#a30000', '#ec7a08', '#f0ab00']}/>
                          </FlexItem>
                          <FlexItem flex={{ default: 'flex_1s' }}>
                              <Table
                                  borders={false}
                                  aria-label='Simple Table'
                                  cells={columns}
                                  rows={rows}
                                  className='ins-m-no-styling'
                                  gridBreakPoint=''>
                                  <TableHeader />
                                  <TableBody />
                              </Table>
                          </FlexItem>
                      </Flex>
                  </TemplateCardBody>
              }/>
      </Card>;
  };
  
  export default VulnerabilityCard;
  