import Model from './model/model';
import { useThree } from '@react-three/fiber';
import { CameraControls } from '@react-three/drei';
import { Vector3 } from 'three';
import { useSelectedFloorItem } from '../../../../store/builder/store';
import { useSelectedAsset } from '../../../../store/simulation/useSimulationStore';
import { useSceneContext } from '../../../scene/sceneContext';

function Models() {
    const { controls } = useThree();
    const { assetStore } = useSceneContext();
    const { assets } = assetStore();
    const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
    const { selectedAsset, clearSelectedAsset } = useSelectedAsset();

    return (
        <group
            name='Asset Group'
            onPointerMissed={(e) => {
                e.stopPropagation();
                if (selectedFloorItem) {
                    const target = (controls as CameraControls).getTarget(new Vector3());
                    (controls as CameraControls).setTarget(target.x, 0, target.z, true);
                    setSelectedFloorItem(null);
                }
                if (selectedAsset) {
                    clearSelectedAsset();
                }
            }}
        >
            {assets.map((asset) =>
                <Model key={asset.modelUuid} asset={asset} />
            )}
        </group>
    )
}

export default Models