import Cylinder, { CylinderGeometry } from "3dModels/Shapes/3D/Cylinder"
import React from "react"
import { Vector3 } from "three"
import CableNode from "./CableNode"
import { Bin } from "models"
import { CableData } from "../../Data/BuildCableData"
import { NodeData } from "../../Data/BuildNodeData"

interface Props {
    cable: CableData
    nodes: NodeData[]
    bin: Bin
    binCenter: Vector3,
    renderOrder?: number,
    displayTemp?: boolean,
    displayMoisture?: boolean
    onNodeClick?: (node: NodeData) => void
}
export default function GrainCable(props: Props) {
    const {cable, nodes, bin, binCenter, onNodeClick, renderOrder, displayTemp, displayMoisture} = props 

    const calculateHeight = () => {
        return cable.topPosition.distanceTo(cable.bottomPosition)
    }

    const calculateCenter = () => {
        return cable.bottomPosition.clone()
            .add(
                cable.topPosition.clone()
                    .sub(cable.bottomPosition)
                    .multiplyScalar(0.5)
            );
    };

    const geometry = React.useMemo(() => ({
        radiusTop: cable.radius,
        radiusBottom: cable.radius,
        height: calculateHeight(),
        radialSegments: cable.radialSegments ?? 10,
        heightSegments: cable.heightSegments ?? 2
    } as CylinderGeometry), [cable]);

    return (
        <React.Fragment>
            <Cylinder geometry={geometry} position={calculateCenter()} opacity={0.5} renderOrder={renderOrder} depthWrite={false} depthTest={false}/>
            {nodes.map((node, i) => (
                <CableNode displayTemp={displayTemp} displayMoisture={displayMoisture} onNodeClick={onNodeClick} key={"node " + i} renderOrder={renderOrder} node={node} binCenter={binCenter} lowerThreshold={bin.lowerTempThreshold()} upperThreshold={bin.upperTempThreshold()}/>
            ))}
        </React.Fragment>
    )
}