import {ForceGraph, GraphData} from './ForceGraph'
import React from 'react'


export type GraphProps = {
    width: number
    height:number
    data:  GraphData
    children : React.ReactNode
}

export const Graph : React.FC<GraphProps> = (props: GraphProps)  => {
    const {data,  width,  height, children} = props

    const graph = React.useMemo(()=>{
        return new ForceGraph(width, height, data) 
    }, [data])


    const [graphDataState, setGraphDataState] = React.useState<GraphData>(data)
    graph.tick = () => {
        setGraphDataState(state => {
            return { 
                nodes: graph.getNodes()
                ,links : state.links
            }
        })
    }
    graph.start()

    return (
        <GraphContext.Provider value={graphDataState}>
            {children}
        </GraphContext.Provider>
    )
}

export const GraphContext = React.createContext<GraphData>({nodes:[], links:[]})