import { Typography } from "@mui/material"
import { Ambient } from "models/Ambient"
import { Controller } from "models/Controller"
import { Plenum } from "models/Plenum"
import React, { useState } from "react"
import PickComponentSet, { ComponentSet } from "./pickComponentSet"
import { cloneDeep } from "lodash"
import { DevicePreset } from "models/DevicePreset"
import { pond } from "protobuf-ts/pond"


interface Props {
  plenums: Plenum[]
  ambients: Ambient[]
  heaters: Controller[]
  fans: Controller[]
  binMode: pond.BinMode
  presets?: DevicePreset[]
  updateSets: (sets: ComponentSet[]) => void
}


export default function ConditioningSelector(props: Props){
  const {plenums, ambients, heaters, fans, updateSets, presets, binMode} = props
  const [currentSets, setCurrentSets] = useState<ComponentSet[]>([])

  const sensorIndex = (key: string) => {
    let index = -1
    currentSets.forEach((set, i) => {
      if(set.sensor.key() === key){
        index = i
      }
    })
    return index
  }

  const setUpdate = (key: string, set?: ComponentSet) => {
    let sets = cloneDeep(currentSets)
    let index = sensorIndex(key)
    //if the set is defined, add it to the existing sets as long as it doesn't already exist
    if(set){
      //check if there is a set that has a sensor with the key
      if(index !== -1){
        sets[index] = set //replace it with the new set
      }else{//if the set was not found ie is new
        sets.push(set)//add the new set
      }
    }else{ //if the set is undefined
      if (index !== -1){
        sets.splice(index, 1)//remove it from the sets
      }
      //no else is needed because if it doesn't exist nothing need be done
    }
    //once the sets are finished being changed pas that up to the parent via the prop function
    setCurrentSets(sets)
    updateSets(sets)
  }
  
  return (
    <React.Fragment>
      {(plenums.length > 0 || ambients.length > 0) &&
        <Typography>Select the sensors you would like to add an interaction to</Typography>
      }
      {plenums.map(plenum => {
        return (
          <PickComponentSet 
            key={plenum.key()} 
            sensor={plenum} 
            heaters={heaters} 
            fans={fans} 
            binMode={binMode}
            presets={presets}
            updateSet={setUpdate} 
          />
      )})}
      {ambients.map(ambient => {
        return (
          <PickComponentSet 
            key={ambient.key()} 
            sensor={ambient} 
            heaters={heaters} 
            fans={fans} 
            binMode={binMode}
            presets={presets}
            updateSet={setUpdate} 
          />
      )})}
    </React.Fragment>
  )
}