commit 36ede89cd7d93c54325f5d1c8adb166cb566fc22
Author: Fantič <58391275+FantaFantic@users.noreply.github.com>
Date:   Mon Nov 13 16:49:09 2023 +0100

    re #10871: PlanViewPage: getSelectedRoom from coordinates: TODO fix coordinates

diff --git a/src/components/plan/CastlePlanView.tsx b/src/components/plan/CastlePlanView.tsx
index 4a0efdf..28f2c4d 100644
--- a/src/components/plan/CastlePlanView.tsx
+++ b/src/components/plan/CastlePlanView.tsx
@@ -1,6 +1,6 @@
 import { Box } from 'native-base';
 import React, { useRef } from 'react';
-import { StyleSheet, Dimensions, TouchableOpacity } from 'react-native';
+import { StyleSheet, Dimensions, TouchableOpacity, GestureResponderEvent } from 'react-native';
 import { PanGestureHandler, PinchGestureHandler, State, TapGestureHandler } from 'react-native-gesture-handler';
 import Animated, {
     useAnimatedGestureHandler,
@@ -11,11 +11,9 @@ import { PlanImage, Room } from '../../types/plan';
 import Svg, { Path, SvgXml, Text } from 'react-native-svg';
 
 // @ts-ignore
-import { pointInSvgPath } from 'point-in-svg-path';
-import { getFloorList } from '../../stores/actions/planThunks';
+import pointInSvgPolygon from "point-in-svg-polygon"
 
-
-const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selectedRoom?: Room, fullScreenMode?: boolean, height?: number }) => {
+const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selectedRoom?: Room, fullScreenMode?: boolean, height?: number, setSelectedRoom?: (room: Room) => void }) => {
 
     const DEFAULT_SCALE = 1
     const MIN_SCALE = 0.95
@@ -25,13 +23,12 @@ const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selected
         width: "100%"
     }
 
-    const { mapImage, roomList, selectedRoom, fullScreenMode, height } = props;
+    const { mapImage, roomList, selectedRoom, fullScreenMode, height, setSelectedRoom } = props;
 
     const panRef = useRef<React.ReactElement>();
     const pinchRef = useRef<React.ReactElement>();
 
     const svgRef = useRef<React.ReactElement>();
-    const pathRefs = useRef<(Path | null)[]>([]);
 
     const translateX = useSharedValue(0);
     const translateY = useSharedValue(0);
@@ -41,13 +38,17 @@ const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selected
 
     const onPanEvent = useAnimatedGestureHandler({
         // handle one finger -> drag / move
-        onStart: (_, ctx: any) => {
-            ctx.startX = translateX.value;
-            ctx.startY = translateY.value;
+        onStart: (event, ctx: any) => {
+            if (event.numberOfPointers === 1) {
+                ctx.startX = translateX.value;
+                ctx.startY = translateY.value;
+            }
         },
         onActive: (event, ctx: any) => {
-            translateX.value = ctx.startX + event.translationX;
-            translateY.value = ctx.startY + event.translationY;
+            if (event.numberOfPointers === 1) {
+                translateX.value = ctx.startX + event.translationX;
+                translateY.value = ctx.startY + event.translationY;
+            }
         },
     });
 
@@ -82,34 +83,81 @@ const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selected
         };
     });
 
-    const handleSvgPress = (event: any) => {
-        const locationX = Number(event.nativeEvent.locationX);
-        const locationY = Number(event.nativeEvent.locationY);
+
+    function calculateStraightLineDistance(x1: number, y1: number, planX: number, planY: number, log?: boolean) {
+        // Apply scale and translations to both points
+
+        const xOffset = 250
+        const yOffset = 120
+
+        const x2 = planX + xOffset
+        const y2 = planY + yOffset
+
+
+        const x_distance = Math.abs(x1 - x2);
+        const y_distance = Math.abs(y1 - y2);
+
+        if (log) {
+            console.log("Original X: ", x1, "Original Y: ", y1);
+            console.log("Clicked X: ", planX, "Clicked Y: ", planY);
+            console.log("Transformed X: ", x2, "Transformed Y: ", y2);
+            console.log("Scale: ", scale.value, "TranslateX: ", translateX.value, "TranslateY: ", translateY.value);
+            console.log("X Distance: ", x_distance, "Y Distance: ", y_distance);
+        }
+        return x_distance + y_distance;
+    }
+
+
+    const handleSvgPress = (event: GestureResponderEvent) => {
+
+        // Get the raw event coordinates
+        const rawLocationX = event.nativeEvent.locationX;
+        const rawLocationY = event.nativeEvent.locationY;
+
+        // Log raw coordinates
+        console.log("Raw Location X: ", rawLocationX, "Raw Location Y: ", rawLocationY);
+
+        // If needed, you can get the SVG element's dimensions to normalize the coordinates
+        const svgWidth = Dimensions.get('window').width
+        const svgHeight = height ? height : (!fullScreenMode ? MAP_VIEW_SIZE.height : Dimensions.get('window').height - 62.5)
+
+        // Normalize the coordinates based on the SVG dimensions
+        // @ts-ignore
+        const locationX = (rawLocationX / svgWidth) * 100;
+        const locationY = (rawLocationY / svgHeight) * 100;
+
 
         // Check if the touch event is within the bounds of a room
         let clickedRoom: Room | undefined = undefined
 
+        // TODO set accordingaly
+        const maxNumberDistance = 100
+
+        let minDistance = Number.MAX_VALUE
+
+        for (let i = 0; i < roomList.length; i++) {
+            const room: Room = roomList[i]
+            if (room.in_plan) {
 
-        for (let i = 0; i < pathRefs.current.length; i++) {
-            const pathRef: Path | null = pathRefs.current[i]
-            const id = pathRef?.props.id
+                const currentDistance = calculateStraightLineDistance(room.number_x, room.number_y, locationX, locationY, true)
 
-            if (id?.startsWith("roomList_")) {
-                const listIndex = parseInt(id.split("roomList_")[1])
-                console.log(listIndex)
-                if (pathRef && pathRef.isPointInFill({ x: locationX, y: locationY })) {
-                    clickedRoom = roomList[listIndex]
+                if (currentDistance < minDistance) {
+                    minDistance = currentDistance
+                    clickedRoom = room
                 }
             }
-
         };
 
-        if (clickedRoom) {
-            // TODO
-            console.log('Room clicked with id:', clickedRoom.id);
+        console.log('Room clicked with id:', clickedRoom.id);
+        console.log(minDistance)
+        if (clickedRoom && minDistance < maxNumberDistance) {
+            // TODO        
+
             // Perform any actions you need with the clicked room
+
+            // TODO fix -> point recognition
+            setSelectedRoom && setSelectedRoom(clickedRoom)
         } else {
-            // TODO
             console.log("no room found")
         }
     };
@@ -176,7 +224,6 @@ const CastlePlanView = (props: { mapImage: PlanImage, roomList: Room[], selected
                                         }
                                         return (
                                             <Path
-                                                ref={(ref) => (pathRefs.current[index] = ref)}
                                                 id={"roomList_" + index.toString()}
                                                 key={'room_' + room.id}
                                                 d={room.svg_path}  // The path data defining the shape of the room
diff --git a/src/pages/PlanViewPage.tsx b/src/pages/PlanViewPage.tsx
index 2326973..5abc3be 100644
--- a/src/pages/PlanViewPage.tsx
+++ b/src/pages/PlanViewPage.tsx
@@ -312,7 +312,11 @@ const PlanViewPage = ({ route, navigation }: DrawerScreenProps<RootDrawerParamLi
                     mr={2.5}
                     onTouchStart={() => setIsInteractingWithCastlePlan(true)}
                     onTouchEnd={() => setIsInteractingWithCastlePlan(true)}>
-                    <CastlePlanView mapImage={floorMapImage} selectedRoom={selectedRoom} roomList={selectedFloor.roomList} height={Dimensions.get("window").height - 350} />
+                    <CastlePlanView mapImage={floorMapImage} selectedRoom={selectedRoom} roomList={selectedFloor.roomList} height={Dimensions.get("window").height - 350} 
+                      setSelectedRoom={(room : Room) => {
+                        selectRoom(room.id)
+                      }}
+                    />
                   </Box>
               )
               }
