import { Box, MenuItem, TextField, Typography } from "@mui/material"
import { extension, getFriendlyName, getSubtypes, Subtype } from "pbHelpers/ComponentType"
import { pond } from "protobuf-ts/pond"
import { quack } from "protobuf-ts/quack"
import React, { useEffect, useState } from "react"
import PortComponent from "./PortComponent"
import { Component } from "models"

interface Props {
  scan: pond.DetectOneWire
  componentSelectionCallback: (newComponents: Component[], checked: boolean) => void
}

export default function ScannedOneWirePort(props: Props){
  const {scan, componentSelectionCallback} = props
  const [portComponents, setPortComponents] = useState<quack.OneWireComponentData[]>([])

  useEffect(()=>{
    setPortComponents(scan.settings?.oneWireData?.components ?? [])
  },[scan])

  const componentSelected = (checked: boolean, componentData: quack.OneWireComponentData) => {
    let newComponents: Component[] = []
    //use the component data to create a new Component
    //build a component with given information and defaults for the rest
    let primaryComponent = Component.create()
    primaryComponent.settings.type = componentData.type
    primaryComponent.settings.subtype = componentData.subtype
    primaryComponent.settings.address = scan.settings?.oneWireData?.port ?? 0
    primaryComponent.settings.addressType = quack.AddressType.ADDRESS_TYPE_CONFIGURABLE_PIN_ARRAY
    primaryComponent.settings.name = getFriendlyName(componentData.type, componentData.subtype)

    //need to check if the component is chainable, meaning the address type will reflect the cable id
    let ext = extension(componentData.type, componentData.subtype)
    if(ext.isChainable){
    primaryComponent.settings.addressType = componentData.cableId + 8
    }
    newComponents.push(primaryComponent)

    componentSelectionCallback(newComponents, checked)
  }

  return (
    <React.Fragment>
      {portComponents.length > 0 ? portComponents.map((compData, i) => {
        return (
          <PortComponent key={i} compData={compData} componentSelect={(checked, component) => {
            componentSelected(checked, component)
          }}/>
        )
      }):
      <Box>
        <Typography>No Components Found</Typography>  
      </Box>}
    </React.Fragment>
  )
}