import { useEffect, useMemo } from 'react';
import { useAisleStore } from '../../../../store/builder/useAisleStore';
import { useToggleView } from '../../../../store/builder/store';
import AisleInstance from './instance/aisleInstance';
import Point from '../../point/point';

function AisleInstances() {
    const { aisles } = useAisleStore();
    const { toggleView } = useToggleView();

    const allPoints = useMemo(() => {
        const points: Point[] = [];
        const seenUuids = new Set<string>();

        aisles.forEach(aisle => {
            aisle.points.forEach(point => {
                if (!seenUuids.has(point.uuid)) {
                    seenUuids.add(point.uuid);
                    points.push(point);
                }
            });
        });

        return points;
    }, [aisles]);

    useEffect(() => {
        // console.log('aisles: ', aisles);
    }, [aisles]);

    return (
        <>
            {toggleView &&
                <group name='Aisle-Points-Group'>
                    {allPoints.map((point) => (
                        <Point key={point.uuid} point={point} />
                    ))}
                </group>
            }

            <group name='Aisles-Group'>
                {aisles.map((aisle) =>
                    <AisleInstance aisle={aisle} key={aisle.uuid} />
                )}
            </group>
        </>
    )
}

export default AisleInstances