Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
8.7 kB
0
Indexable
Never
"use client";
import { useEffect, useState } from "react";
import { io } from "socket.io-client";
import { IDatePicker } from "../../../../../types";

let intervalId: NodeJS.Timeout;

const socket = io(process.env.NEXT_PUBLIC_SOCKET_URL!, {
  withCredentials: true
});

function toISOString(date: any) {
  return new Date(new Date(date).setUTCHours(0, 0, 0, 0)).toISOString();
}

export default function useBooking() {
  const [tempHoldRooms, setTempHoldRooms] = useState<any>();
  const [availableRoom, setAvailableRoom] = useState<any>();
  const [holdData, setHoldData] = useState<any>();
  const currentDate = new Date(new Date(new Date()).setUTCHours(0, 0, 0, 0)).toISOString();
  const [pickerDate, setPickerDate] = useState<IDatePicker>({
    startDate: new Date().toISOString(),
    endDate: new Date(new Date(currentDate).getTime() + 24 * 60 * 60 * 1000).toISOString()
  });

  useEffect(() => {
    socket.on("connect", () => {});

    socket.on("hold", (data: any) => {
      console.log("socketEvent", data);
      // if (data && toISOString(pickerDate.startDate) === data.date) {
      //   const ownHoldIds = data.ownHold.map((hold: any) => hold.id);
      //   const nonExistentHolds = data.totalHolds.filter((hold: any) => !ownHoldIds.includes(hold));

      //   const notOwnHold = data.totalHolds.filter((id: any) => !data.ownHold.some((hold: any) => hold.id === id));

      //   setAvailableRoom((prevRooms: any) =>
      //     prevRooms.map((room: any) => ({
      //       ...room,

      //       hold: notOwnHold.includes(room.id) ? true : nonExistentHolds.includes(room.id) && false
      //     }))
      //   );
      // }

      // ===========v2=========

      // if (data && toISOString(pickerDate.startDate) === data.date) {
      //   const ownHoldIds = new Set(data.ownHold.map((hold: any) => hold.id));
      //   const nonExistentHolds = data.totalHolds.filter((hold: any) => !ownHoldIds.has(hold));

      //   const notOwnHold = data.totalHolds.filter((id: any) => !ownHoldIds.has(id));

      //   setAvailableRoom((prevRooms: any) =>
      //     prevRooms.map((room: any) => ({
      //       ...room,
      //       hold: notOwnHold.includes(room.id) ? true : nonExistentHolds.includes(room.id) && false
      //     }))
      //   );
      // }

      // ============v3=========

      if (data && toISOString(pickerDate.startDate) === data.date) {
        // Extract own hold IDs
        const ownHoldIds = new Set(data.ownHold.map((hold: any) => hold.id));

        // Get all hold IDs
        const totalHoldIds = new Set(data.totalHolds);

        // Determine holds that are not owned by the current user
        const notOwnHolds = Array.from(totalHoldIds).filter(holdId => !ownHoldIds.has(holdId));

        // Update available rooms
        setAvailableRoom((prevRooms: any) =>
          prevRooms.map((room: any) => ({
            ...room,
            hold: notOwnHolds.includes(room.id)
          }))
        );
      }
    });

    socket.on("room-status", (data: any) => {
      console.log("room-status", data);

      // if (data && toISOString(pickerDate.startDate) === data.date) {
      //   const ownHoldIds = new Set(data.ownHold.map((hold: any) => hold.id));
      //   const nonExistentHolds = data.totalHolds.filter((hold: any) => !ownHoldIds.has(hold));
      //   console.log(ownHoldIds, "ownHoldIds");

      //   const notOwnHold = data.totalHolds.filter((id: any) => !ownHoldIds.has(id));

      //   setAvailableRoom((prevRooms: any) =>
      //     prevRooms.map((room: any) => {
      //       const isNotOwnHold = notOwnHold.includes(room.id);
      //       const isNonExistentHold = nonExistentHolds.includes(room.id);
      //       // console.log(isNotOwnHold, "isNotOwnHold");
      //       // console.log(isNonExistentHold, "isNonExistentHold");

      //       // console.log(isNotOwnHold ? true : isNonExistentHold && false, "main");

      //       return {
      //         ...room,
      //         hold: isNotOwnHold ? true : isNonExistentHold && false,
      //         // selected: ownHoldIds.includes(room.id) ? true :false
      //         selected: ownHoldIds.has(room.id) ? true : false
      //       };
      //     })
      //   );
      // }

      // =============v2=======

      if (data && toISOString(pickerDate.startDate) === data.date) {
        // Extract own hold IDs
        const ownHoldIds = new Set(data.ownHold.map((hold: any) => hold.id));

        // Determine holds that are not owned by the current user
        const notOwnHoldIds = new Set(data.totalHolds.filter((id: any) => !ownHoldIds.has(id)));

        setAvailableRoom((prevRooms: any) =>
          prevRooms.map((room: any) => {
            const isNotOwnHold = notOwnHoldIds.has(room.id);
            const isOwnHold = ownHoldIds.has(room.id);

            return {
              ...room,
              hold: isNotOwnHold,
              selected: isOwnHold
            };
          })
        );
      }
    });

    socket.on("booking", (data: any) => {
      console.log("bookingEvent", data);
    });

    intervalId = setInterval(() => {
      socket.emit("status", { date: toISOString(pickerDate.startDate) });
    }, 5000);

    return () => {
      socket.off("connect");
      socket.off("hold");
      socket.off("booking");
      socket.off("room-status");
      clearInterval(intervalId);
    };
  }, []);

  // useEffect(() => {
  //   // get all rooms
  //   // get available rooms (date field in query)
  //   // get temporary hold (date field in query)

  //   intervalId = setInterval(() => {
  //     socket.emit("status", { date: toISOString(pickerDate.startDate) });
  //   }, 5000);

  //   return () => clearInterval(intervalId);
  // }, [pickerDate.startDate]);

  const handleImageClick = (id: number, index: number) => {
    setAvailableRoom((prevRooms: any) => prevRooms?.map((room: any) => (room.id === id ? { ...room, selected: !room.selected } : room)));
    console.log(id, "id");

    socket.emit("hold", {
      date: toISOString(pickerDate.startDate),
      rooms: [id]
    });
  };
  console.log(availableRoom, "availableRoom");

  return {
    socket,
    availableRoom,
    setAvailableRoom,
    holdData,
    setHoldData,
    pickerDate,
    setPickerDate,
    toISOString,
    handleImageClick,
    tempHoldRooms,
    setTempHoldRooms
  };
}

// //v2=----------------
// import { createContext, useContext, useState, useEffect, ReactNode } from "react";
// import { io, Socket } from "socket.io-client";

// interface SocketContextProps {
//   socket: Socket | null;
//   holdData: any;
// }

// const SocketContext = createContext<SocketContextProps>({
//   socket: null,
//   holdData: null
// });

// export const SocketProvider = ({ children }: { children: ReactNode }) => {
//   const [socket] = useState(() => io(process.env.NEXT_PUBLIC_SOCKET_URL!, { withCredentials: true }));
//   const [holdData, setHoldData] = useState<any>(null);

//   useEffect(() => {
//     socket.on("connect", () => {});

//     socket.on("hold", (data: any) => {
//       console.log("socketEvent", data);
//       setHoldData(data);
//     });

//     socket.on("booking", (data: any) => {
//       console.log("bookingEvent", data);
//     });

//     return () => {
//       socket.off("connect");
//       socket.off("hold");
//       socket.off("booking");
//     };
//   }, [socket]);

//   return <SocketContext.Provider value={{ socket, holdData }}>{children}</SocketContext.Provider>;
// };

// export const useSocket = () => useContext(SocketContext);

//v2=----------------

// new Date(new Date("2024-07-18T11:15:03.767Z").setUTCHours(0,0,0,0)).toISOString()
// for booking event
// {
//   "date": "2024-07-24T00:00:00.000Z",
//   "ownHold": [],
//   "availableRooms": [
//       "667cfadea1f9993f34e342ab",
//       "667cfaeca1f9993f34e342ad",
//       "667cfaf4a1f9993f34e342af",
//       "667cfafea1f9993f34e342b1",
//       "667cfb09a1f9993f34e342b3"
//   ],
//   "totalHolds": []
// }

// hold event
// {
//   "date": "2024-07-18T11:15:03.767Z",
//   "ownHold": [
//       {
//           "id": "667cfb09a1f9993f34e342b3",
//           "time": "5 m 7 s"
//       },
//       {
//           "id": "667cfaf4a1f9993f34e342af",
//           "time": "15 m "
//       }
//   ],
//   "totalHolds": [
//       "667cfb09a1f9993f34e342b3",
//       "667cfaf4a1f9993f34e342af"
//   ]
// }
Leave a Comment