import { useProductContext } from "../../../products/productContext";
import { useSceneContext } from "../../../../scene/sceneContext";

import PointInstance from "./instance/pointInstance";

function PointInstances() {
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();

    const { eventStore, productStore } = useSceneContext();
    const { events } = eventStore();
    const { getEventByModelUuid } = productStore();

    const colorByType: Record<string, string> = {
        transfer: "orange",
        vehicle: "blue",
        roboticArm: "green",
        machine: "purple",
        storageUnit: "red",
        human: "white",
    };

    return (
        <>
            {events.map((event, index) => {
                const updatedEvent = selectedProduct.productUuid !== '' ? getEventByModelUuid(selectedProduct.productUuid, event.modelUuid) : null;

                const usedEvent = updatedEvent || event;
                const color = colorByType[usedEvent.type];

                if (!color) return null;

                const points = usedEvent.type === "transfer" ? usedEvent.points : [usedEvent.point];

                return (
                    <group
                        key={`${index}-${usedEvent.modelUuid}`}
                        position={usedEvent.position}
                        rotation={usedEvent.rotation}
                    >
                        {points.map((point) => (
                            <PointInstance
                                key={point.uuid}
                                point={point}
                                modelUuid={usedEvent.modelUuid}
                                color={color}
                            />
                        ))}
                    </group>
                );
            })}
        </>
    );
}

export default PointInstances;
