All files / modules/75-ce/components/COGatewayConfig/steps/ManageResources ManageResources.tsx

68.05% Statements 164/241
61.97% Branches 88/142
61.54% Functions 32/52
68.05% Lines 164/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647              4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                       4x                                                                                                   4x 33x 31x 31x 31x 31x   31x 31x 31x 31x 31x     31x 31x 31x   31x 31x 31x 31x 31x   31x                 31x               31x                 31x 11x     11x         11x 9x       31x   11x         31x 11x     31x 3x                       31x 8x                       31x 9x                   31x 9x                 31x 1x 1x       31x 11x     6x       6x 6x 6x 6x       1x   1x 1x 1x 1x                     2x 2x 2x 2x 2x                                     11x 9x       31x 7x                         31x 6x 6x                   6x   1x 1x     6x           31x 1x 1x 1x 1x 1x 1x             31x 2x 2x       1x 1x 1x 1x 1x 1x   1x     1x       31x                                                           31x 1x       1x 1x                                         31x 1x     1x     31x 2x                                 31x                                       31x                                       31x 1x 1x 1x                 31x                       31x       31x 3x 3x               3x 3x       31x                         31x 31x   248x 248x     124x                   31x                                                                                           4x 30x   30x 28x               28x     30x 28x               28x     30x 2x   28x                       4x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { isEmpty as _isEmpty, omit as _omit, defaultTo as _defaultTo } from 'lodash-es'
import { Radio, RadioGroup } from '@blueprintjs/core'
import { Layout, Text } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { useStrings } from 'framework/strings'
import { CONFIG_STEP_IDS, CONFIG_TOTAL_STEP_COUNTS, DEFAULT_ACCESS_DETAILS, RESOURCES } from '@ce/constants'
import { FeatureFlag } from '@common/featureFlags'
import type { GatewayDetails, InstanceDetails } from '@ce/components/COCreateGateway/models'
import type { StringsMap } from 'stringTypes'
import COK8sClusterSelector from '@ce/components/COK8sClusterSelector/COK8sClusterSelector'
import { ConnectorInfoDTO, ConnectorResponse, useGetConnectorListV2 } from 'services/cd-ng'
import { ASGMinimal, PortConfig, useAllResourcesOfAccount, useGetAllASGs, ContainerSvc, RDSDatabase } from 'services/lw'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useToaster } from '@common/exports'
import COInstanceSelector from '@ce/components/COInstanceSelector/COInstanceSelector'
import COEcsSelector from '@ce/components/COEcsSelector/COEcsSelector'
import COAsgSelector from '@ce/components/COAsgSelector'
import { Connectors } from '@connectors/constants'
import { Utils } from '@ce/common/Utils'
import CORdsSelector from '@ce/components/CORdsSelector/CORdsSelector'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import { useGatewayContext } from '@ce/context/GatewayContext'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import COGatewayConfigStep from '../../COGatewayConfigStep'
import { fromResourceToInstanceDetails, isFFEnabledForResource } from '../../helper'
import ResourceSelectionModal from '../../ResourceSelectionModal'
import { DisplaySelectedConnector } from './DisplaySelectedConnector'
import { DisplaySelectedASG } from './DisplaySelectedASG'
import { DisplaySelectedInstances } from './DisplaySelectedInstances'
import { DisplaySelectedEcsService } from './DisplaySelectedEcsService'
import { DisplaySelectedRdsDatabse } from './DisplaySelectedRdsDatabase'
import css from '../../COGatewayConfig.module.scss'
 
interface ManageResourcesProps {
  setDrawerOpen: (shouldOpen: boolean) => void
  totalStepsCount: number
  gatewayDetails: GatewayDetails
  setGatewayDetails: (details: GatewayDetails) => void
  setTotalStepsCount: (stepCount: number) => void
  selectedResource: RESOURCES | null
  setSelectedResource: (resource: RESOURCES) => void
}
 
const managedResources = [
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.ec2Vms',
    value: RESOURCES.INSTANCES,
    providers: ['aws']
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.vms',
    value: RESOURCES.INSTANCES,
    providers: ['azure']
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.gcpVms',
    value: RESOURCES.INSTANCES,
    providers: ['gcp'],
    ffDependencies: [FeatureFlag.CE_AS_GCP_VM_SUPPORT]
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.asg',
    value: RESOURCES.ASG,
    providers: ['aws']
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.ig',
    value: RESOURCES.IG,
    providers: ['gcp'],
    ffDependencies: [FeatureFlag.CE_AS_GCP_VM_SUPPORT]
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.kubernetes',
    value: RESOURCES.KUBERNETES,
    providers: ['aws', 'azure', 'gcp'],
    ffDependencies: [
      FeatureFlag.CE_AS_KUBERNETES_ENABLED,
      FeatureFlag.CE_AS_KUBERNETES_ENABLED,
      FeatureFlag.CE_AS_KUBERNETES_ENABLED
    ]
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.ecsService',
    value: RESOURCES.ECS,
    providers: ['aws']
  },
  {
    label: 'ce.co.autoStoppingRule.helpText.step2.description.resourceList.rdsInstances',
    value: RESOURCES.RDS,
    providers: ['aws']
  }
]
 
const ManageResources: React.FC<ManageResourcesProps> = props => {
  const { getString } = useStrings()
  const { accountId } = useParams<ProjectPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const { showError } = useToaster()
  const { trackEvent } = useTelemetry()
 
  const [allConnectors, setAllConnectors] = useState<ConnectorResponse[]>([])
  const [connectorsToShow, setConnectorsToShow] = useState<ConnectorResponse[]>([])
  const [asgToShow, setAsgToShow] = useState<ASGMinimal[]>([])
  const [allAsg, setAllAsg] = useState<ASGMinimal[]>([])
  const [selectedAsg, setSelectedAsg] = useState<ASGMinimal | undefined>(
    props.gatewayDetails.routing?.instance?.scale_group
  )
  const [allInstances, setAllInstances] = useState<InstanceDetails[]>([])
  const [selectedInstances, setSelectedInstances] = useState<InstanceDetails[]>(props.gatewayDetails.selectedInstances)
  const [selectedConnector, setSelectedConnector] = useState<ConnectorResponse | undefined>()
 
  const isAwsProvider = Utils.isProviderAws(props.gatewayDetails.provider)
  const isAzureProvider = Utils.isProviderAzure(props.gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(props.gatewayDetails.provider)
  const featureFlagsMap = useFeatureFlags()
  const { isEditFlow } = useGatewayContext()
 
  const { mutate: getInstances, loading: loadingInstances } = useAllResourcesOfAccount({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: props.gatewayDetails.cloudAccount.id, // eslint-disable-line
      type: 'instance',
      accountIdentifier: accountId
    }
  })
 
  const { mutate: fetchAllASGs, loading: loadingFetchASGs } = useGetAllASGs({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: props.gatewayDetails.cloudAccount.id, // eslint-disable-line
      accountIdentifier: accountId
    }
  })
 
  const { mutate: fetchConnectors, loading: loadingConnectors } = useGetConnectorListV2({
    queryParams: {
      accountIdentifier: accountId,
      searchTerm: '',
      pageIndex: 0,
      pageSize: 100
    }
  })
 
  useEffect(() => {
    Iif (!props.gatewayDetails.provider) {
      return
    }
    const resourcesFetchMap: Record<string, () => void> = {
      [RESOURCES.INSTANCES]: Utils.getConditionalResult(isAwsProvider, refreshInstances, undefined),
      [RESOURCES.ASG]: fetchAndSetAsgItems,
      [RESOURCES.KUBERNETES]: fetchAndSetConnectors
    }
    if (props.selectedResource) {
      resourcesFetchMap[props.selectedResource]?.()
    }
  }, [props.gatewayDetails.provider, props.selectedResource])
 
  useEffect(() => {
    // run only in case of selecting instances
    Iif (props.selectedResource === RESOURCES.INSTANCES && !selectedInstances.length) {
      setRoutingRecords([])
    }
  }, [selectedInstances])
 
  useEffect(() => {
    clearResourceDetailsFromGateway(props.selectedResource as RESOURCES)
  }, [props.selectedResource])
 
  const resetSelectedInstancesDetails = () => {
    Iif (!_isEmpty(props.gatewayDetails.selectedInstances)) {
      setRoutingRecords([])
      setSelectedInstances([])
      const updatedGatewayDetails = {
        ...props.gatewayDetails,
        metadata: { ...props.gatewayDetails.metadata, access_details: DEFAULT_ACCESS_DETAILS },
        selectedInstances: []
      }
      props.setGatewayDetails(updatedGatewayDetails)
    }
  }
 
  const resetSelectedAsgDetails = () => {
    Iif (!_isEmpty(props.gatewayDetails.routing.instance.scale_group)) {
      setRoutingRecords([])
      setSelectedAsg(undefined)
      const updatedGatewayDetails = {
        ...props.gatewayDetails,
        metadata: { ...props.gatewayDetails.metadata, access_details: DEFAULT_ACCESS_DETAILS }
      }
      delete updatedGatewayDetails.routing.instance.scale_group
      props.setGatewayDetails(updatedGatewayDetails)
    }
  }
 
  const resetSelectedEcsDetails = () => {
    Iif (!_isEmpty(props.gatewayDetails.routing.container_svc)) {
      const updatedGatewayDetails: GatewayDetails = {
        ...props.gatewayDetails,
        resourceMeta: undefined,
        routing: { ...props.gatewayDetails.routing, container_svc: undefined }
      }
      props.setGatewayDetails(updatedGatewayDetails)
    }
  }
 
  const resetSelectedRdsDetails = () => {
    Iif (!_isEmpty(props.gatewayDetails.routing.database)) {
      const updatedGatewayDetails: GatewayDetails = {
        ...props.gatewayDetails,
        routing: { ...props.gatewayDetails.routing, database: undefined }
      }
      props.setGatewayDetails(updatedGatewayDetails)
    }
  }
 
  const handleErrorDisplay = (e: any, fallbackMsgKey?: string) => {
    Eif (!Utils.isUserAbortedRequest(e)) {
      showError(getRBACErrorMessage(e), undefined, fallbackMsgKey)
    }
  }
 
  const clearResourceDetailsFromGateway = (resourceType: RESOURCES) => {
    const resourceToFunctionalityMap: Record<string, () => void> = {
      [RESOURCES.INSTANCES]: () => {
        // set total no. of steps to default (4)
        props.setTotalStepsCount(
          Utils.getConditionalResult(isGcpProvider, CONFIG_TOTAL_STEP_COUNTS.MODIFIED, CONFIG_TOTAL_STEP_COUNTS.DEFAULT)
        )
        // remove details related to AsG
        resetSelectedAsgDetails()
        resetKubernetesConnectorDetails()
        resetSelectedEcsDetails()
        resetSelectedRdsDetails()
      },
      [RESOURCES.ASG]: () => {
        // set total no. of steps to default (4)
        props.setTotalStepsCount(CONFIG_TOTAL_STEP_COUNTS.DEFAULT)
        // remove details related to instances
        resetSelectedInstancesDetails()
        resetKubernetesConnectorDetails()
        resetSelectedEcsDetails()
        resetSelectedRdsDetails()
      },
      [RESOURCES.IG]: () => {
        // set total no. of steps to default (4)
        props.setTotalStepsCount(CONFIG_TOTAL_STEP_COUNTS.DEFAULT)
        // remove details related to instances
        resetSelectedInstancesDetails()
        resetKubernetesConnectorDetails()
      },
      [RESOURCES.KUBERNETES]: () => {
        // set total no. of steps to modified (3)
        props.setTotalStepsCount(CONFIG_TOTAL_STEP_COUNTS.MODIFIED)
        resetSelectedInstancesDetails()
        resetSelectedAsgDetails()
        resetSelectedEcsDetails()
        resetSelectedRdsDetails()
      },
      [RESOURCES.ECS]: () => {
        props.setTotalStepsCount(CONFIG_TOTAL_STEP_COUNTS.DEFAULT)
        resetSelectedInstancesDetails()
        resetSelectedAsgDetails()
        resetKubernetesConnectorDetails()
        resetSelectedRdsDetails()
      },
      [RESOURCES.RDS]: () => {
        props.setTotalStepsCount(CONFIG_TOTAL_STEP_COUNTS.MODIFIED)
        resetSelectedInstancesDetails()
        resetSelectedAsgDetails()
        resetKubernetesConnectorDetails()
        resetSelectedEcsDetails()
        resetSelectedRdsDetails()
      }
    }
 
    if (resourceType) {
      resourceToFunctionalityMap[resourceType]?.()
    }
  }
 
  const resetKubernetesConnectorDetails = () => {
    Iif (!_isEmpty(props.gatewayDetails.metadata.kubernetes_connector_id)) {
      setSelectedConnector(undefined)
      const updatedRouting = _omit(props.gatewayDetails.routing, 'k8s')
      const updatedMetadata = _omit(props.gatewayDetails.metadata, 'kubernetes_connector_id')
      const updatedGatewayDetails: GatewayDetails = {
        ...props.gatewayDetails,
        routing: updatedRouting,
        metadata: updatedMetadata
      }
      props.setGatewayDetails(updatedGatewayDetails)
    }
  }
 
  const refreshInstances = async (textTomlString = ''): Promise<void> => {
    try {
      const result = await getInstances(
        { Text: textTomlString },
        {
          queryParams: {
            cloud_account_id: props.gatewayDetails.cloudAccount.id, // eslint-disable-line
            type: 'instance',
            accountIdentifier: accountId
          }
        }
      )
      const instances = _defaultTo(
        result?.response
          ?.filter(x => x.status !== 'terminated')
          .map(item => fromResourceToInstanceDetails(item, { isAzure: isAzureProvider, isGcp: isGcpProvider })),
        []
      )
      setAllInstances(instances)
    } catch (e) {
      handleErrorDisplay(e, 'ce.refetch.instance.error')
    }
  }
 
  const fetchAndSetAsgItems = async (text = ''): Promise<void> => {
    try {
      const result = await fetchAllASGs({ Text: text })
      Eif (result?.response) {
        const filteredAsgs = result.response || []
        setAllAsg(filteredAsgs)
        setAsgToShow(filteredAsgs)
      }
    } catch (err) {
      handleErrorDisplay(err, 'ce.fetchAndSetAsgItems.error')
    }
  }
 
  const fetchAndSetConnectors = async () => {
    try {
      const { data: connectorResponse } = await fetchConnectors({
        filterType: 'Connector',
        types: [Connectors.CE_KUBERNETES]
      })
      const content = connectorResponse?.content
      Eif (!_isEmpty(content)) {
        setAllConnectors(content as ConnectorResponse[])
        setConnectorsToShow(content as ConnectorResponse[])
        const prevSelectedConnector = (content as ConnectorResponse[]).find(
          _item => _item.connector?.identifier === props.gatewayDetails.metadata.kubernetes_connector_id
        )
        prevSelectedConnector && setSelectedConnector(prevSelectedConnector)
      }
    } catch (e) {
      handleErrorDisplay(e)
    }
  }
 
  const [openClusterModal, closeClusterModal] = useModalHook(() => {
    return (
      <ResourceSelectionModal
        closeBtnTestId={'close-connector-modal'}
        onClose={() => {
          handleConnectorsSearch('')
          closeClusterModal()
        }}
      >
        <COK8sClusterSelector
          loading={loadingConnectors}
          clusters={connectorsToShow}
          search={handleConnectorsSearch}
          selectedCluster={selectedConnector}
          refetchConnectors={fetchAndSetConnectors}
          onClusterAddSuccess={cluster => {
            const updatedGatewayDetails: GatewayDetails = {
              ...props.gatewayDetails,
              metadata: { ...props.gatewayDetails.metadata, kubernetes_connector_id: cluster.connector?.identifier }
            }
            props.setGatewayDetails(updatedGatewayDetails)
            setSelectedConnector(cluster)
            handleConnectorsSearch('')
            closeClusterModal()
          }}
        />
      </ResourceSelectionModal>
    )
  }, [allConnectors, connectorsToShow, selectedConnector, loadingConnectors, props.gatewayDetails])
 
  const [openAsgModal, closeAsgModal] = useModalHook(() => {
    return (
      <ResourceSelectionModal
        closeBtnTestId={'close-asg-modal'}
        onClose={() => {
          handleAsgSearch('')
          closeAsgModal()
        }}
      >
        <COAsgSelector
          selectedScalingGroup={selectedAsg}
          setSelectedAsg={setSelectedAsg}
          scalingGroups={asgToShow}
          gatewayDetails={props.gatewayDetails}
          search={handleAsgSearch}
          onAsgAddSuccess={updatedGatewayDetails => {
            props.setGatewayDetails(updatedGatewayDetails)
            handleAsgSearch('')
            closeAsgModal()
          }}
          loading={loadingFetchASGs}
          refresh={fetchAndSetAsgItems}
        />
      </ResourceSelectionModal>
    )
  }, [allAsg, asgToShow, selectedAsg, loadingFetchASGs, props.gatewayDetails])
 
  const onInstanceModalClose = () => {
    Iif (isAzureProvider) {
      setAllInstances([])
    }
    closeInstancesModal()
  }
 
  const [openInstancesModal, closeInstancesModal] = useModalHook(() => {
    return (
      <ResourceSelectionModal closeBtnTestId={'close-instance-modal'} onClose={onInstanceModalClose}>
        <COInstanceSelector
          selectedInstances={selectedInstances}
          setSelectedInstances={setSelectedInstances}
          setGatewayDetails={props.setGatewayDetails}
          instances={allInstances}
          gatewayDetails={props.gatewayDetails}
          onInstancesAddSuccess={onInstanceModalClose}
          loading={loadingInstances}
          refresh={refreshInstances}
          isEditFlow={isEditFlow}
        />
      </ResourceSelectionModal>
    )
  }, [allInstances, selectedInstances, loadingInstances, props.gatewayDetails, isEditFlow])
 
  const [openEcsModal, closeEcsModal] = useModalHook(
    () => (
      <ResourceSelectionModal
        closeBtnTestId={'close-ecs-modal'}
        onClose={() => {
          closeEcsModal()
        }}
      >
        <COEcsSelector
          gatewayDetails={props.gatewayDetails}
          setGatewayDetails={props.setGatewayDetails}
          onServiceAddSuccess={() => {
            closeEcsModal()
          }}
        />
      </ResourceSelectionModal>
    ),
    [props.gatewayDetails]
  )
 
  const [openRdsModal, closeRdsModal] = useModalHook(
    () => (
      <ResourceSelectionModal
        closeBtnTestId={'close-rds-modal'}
        onClose={() => {
          closeRdsModal()
        }}
      >
        <CORdsSelector
          gatewayDetails={props.gatewayDetails}
          setGatewayDetails={props.setGatewayDetails}
          onDbAddSuccess={() => {
            closeRdsModal()
          }}
        />
      </ResourceSelectionModal>
    ),
    [props.gatewayDetails]
  )
 
  const handleAsgSearch = (text: string) => {
    Eif (!text) {
      setAsgToShow(allAsg)
      return
    }
    text = text.toLowerCase()
    const filteredScalingGroups = allAsg.filter(
      item => item.name?.toLowerCase().includes(text) || item.id?.toLowerCase().includes(text)
    )
    setAsgToShow(filteredScalingGroups)
  }
 
  const handleConnectorsSearch = (text: string) => {
    if (!text) {
      setConnectorsToShow(allConnectors)
      return
    }
    text = text.toLowerCase()
    const filteredConnectors = allConnectors.filter(item =>
      (item.connector as ConnectorInfoDTO).name?.toLowerCase().includes(text)
    )
    setConnectorsToShow(filteredConnectors)
  }
 
  const setRoutingRecords = (records: PortConfig[]) => {
    props.setGatewayDetails({ ...props.gatewayDetails, routing: { ...props.gatewayDetails.routing, ports: records } })
  }
 
  const openSelectedResourceModal = () => {
    const resource = props.selectedResource?.valueOf()
    const modalCbMap: Record<string, () => void> = {
      [RESOURCES.INSTANCES]: openInstancesModal,
      [RESOURCES.ASG]: openAsgModal,
      [RESOURCES.IG]: openAsgModal,
      [RESOURCES.KUBERNETES]: openClusterModal,
      [RESOURCES.ECS]: openEcsModal,
      [RESOURCES.RDS]: openRdsModal
    }
    Eif (resource) {
      modalCbMap[resource]?.()
    }
  }
 
  const handleDeletion = (rowIndex: number) => {
    const instances = [...selectedInstances]
    instances.splice(rowIndex, 1)
    if (instances.length) {
      const updatedGatewayDetails = { ...props.gatewayDetails }
      updatedGatewayDetails.selectedInstances = instances
      props.setGatewayDetails(updatedGatewayDetails)
      setSelectedInstances(instances)
    } else {
      resetSelectedInstancesDetails()
    }
  }
 
  const renderResourcesToManage = () => {
    return managedResources
      .filter(resource => {
        const providerIndex = resource.providers.indexOf(props.gatewayDetails.provider.value)
        return providerIndex > -1 && isFFEnabledForResource(resource.ffDependencies?.[providerIndex], featureFlagsMap)
      })
      .map(resourceItem => {
        return (
          <Radio
            key={resourceItem.value}
            label={getString(resourceItem.label as keyof StringsMap)}
            value={resourceItem.value}
          />
        )
      })
  }
 
  return (
    <COGatewayConfigStep
      count={2}
      title={getString('ce.co.autoStoppingRule.configuration.step2.title')}
      onInfoIconClick={() => props.setDrawerOpen(true)}
      subTitle={getString('ce.co.autoStoppingRule.configuration.step2.subTitle')}
      totalStepsCount={props.totalStepsCount}
      id={CONFIG_STEP_IDS[1]}
    >
      <Layout.Vertical className={css.step2Container}>
        <Text className={css.radioGroupTitle}>Select the resources to be managed by the rule</Text>
        <RadioGroup
          selectedValue={props.selectedResource?.valueOf()}
          onChange={e => {
            trackEvent(USER_JOURNEY_EVENTS.SELECT_MANAGED_RESOURCES, { type: e.currentTarget.value })
            props.setSelectedResource(e.currentTarget.value as RESOURCES)
          }}
          className={css.radioGroup}
        >
          {renderResourcesToManage()}
        </RadioGroup>
        <DisplayResourceInfo
          selectedResource={props.selectedResource as RESOURCES}
          onCtaClick={openSelectedResourceModal}
        />
        {!_isEmpty(selectedInstances) && (
          <DisplaySelectedInstances data={selectedInstances} onDelete={handleDeletion} />
        )}
        {!_isEmpty(selectedAsg) && <DisplaySelectedASG data={[selectedAsg as ASGMinimal]} />}
        {!_isEmpty(selectedConnector) && <DisplaySelectedConnector data={[selectedConnector as ConnectorResponse]} />}
        {!_isEmpty(props.gatewayDetails.resourceMeta?.container_svc) && (
          <DisplaySelectedEcsService data={[props.gatewayDetails.resourceMeta?.container_svc as ContainerSvc]} />
        )}
        {!_isEmpty(props.gatewayDetails.routing.database) && (
          <DisplaySelectedRdsDatabse data={[props.gatewayDetails.routing.database as RDSDatabase]} />
        )}
      </Layout.Vertical>
    </COGatewayConfigStep>
  )
}
 
interface DisplayResourceInfoProps {
  selectedResource: RESOURCES
  onCtaClick: () => void
}
 
const DisplayResourceInfo: React.FC<DisplayResourceInfoProps> = props => {
  const { getString } = useStrings()
 
  const getSelectedResourceText = (resource: string) => {
    const textMap: Record<string, string> = {
      [RESOURCES.INSTANCES]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.instance'),
      [RESOURCES.ASG]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.asg'),
      [RESOURCES.IG]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.ig'),
      [RESOURCES.KUBERNETES]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.kubernetes'),
      [RESOURCES.ECS]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.ecs'),
      [RESOURCES.RDS]: getString('ce.co.autoStoppingRule.configuration.step2.additionalResourceInfo.rds')
    }
    return textMap[resource]
  }
 
  const getSelectedResourceModalCta = (resource: string) => {
    const textMap: Record<string, string> = {
      [RESOURCES.INSTANCES]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.instance')}`,
      [RESOURCES.ASG]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.asg')}`,
      [RESOURCES.IG]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.ig')}`,
      [RESOURCES.KUBERNETES]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.kubernetes')}`,
      [RESOURCES.ECS]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.ecs')}`,
      [RESOURCES.RDS]: `+ ${getString('ce.co.autoStoppingRule.configuration.step2.addResourceCta.rds')}`
    }
    return textMap[resource]
  }
 
  if (_isEmpty(props.selectedResource)) {
    return null
  }
  return (
    <Layout.Vertical style={{ marginBottom: 20 }}>
      <Text style={{ fontSize: 14, color: '#9293AB', marginBottom: 10 }}>
        {getSelectedResourceText(props.selectedResource?.valueOf() as string)}
      </Text>
      <Text style={{ cursor: 'pointer', color: '#0278D5' }} onClick={props.onCtaClick}>
        {getSelectedResourceModalCta(props.selectedResource?.valueOf() as string)}
      </Text>
    </Layout.Vertical>
  )
}
 
export default ManageResources