File size: 2,516 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import React, { createContext, useContext, useEffect, useState } from 'react';
import { io } from 'socket.io-client';
import { useAuth } from './AuthContext';

const SocketContext = createContext(null);

export const useSocket = () => {
  const context = useContext(SocketContext);
  if (!context) {
    throw new Error('useSocket must be used within a SocketProvider');
  }
  return context;
};

export const SocketProvider = ({ children }) => {
  const [socket, setSocket] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const { user } = useAuth();

  useEffect(() => {
    if (!user) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    console.log('🔧 Setting up socket connection for user:', user.id);
    
    const token = localStorage.getItem('token');
    // استفاده از متغیر محیطی برای URL اتصال
    const socketUrl = import.meta.env.VITE_WS_URL || 'http://localhost:5000';
    
    const newSocket = io(socketUrl, {
      auth: {
        token: token
      },
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });

    newSocket.on('connect', () => {
      console.log('✅ Socket connected successfully:', newSocket.id);
      setIsConnected(true);
      setIsLoading(false);
    });

    newSocket.on('disconnect', () => {
      console.log('🔌 Socket disconnected');
      setIsConnected(false);
    });

    newSocket.on('connect_error', (error) => {
      console.error('❌ Socket connection error:', error.message || error);
      setIsConnected(false);
      setIsLoading(false);
    });

    newSocket.on('connect_timeout', () => {
      console.error('❌ Socket connection timeout');
      setIsConnected(false);
      setIsLoading(false);
    });

    newSocket.on('reconnect_attempt', (attempt) => {
      console.log(`🔄 Socket reconnect attempt #${attempt}`);
    });

    setSocket(newSocket);

    return () => {
      console.log('🔌 Cleaning up socket connection');
      newSocket.close();
      setSocket(null);
      setIsConnected(false);
      setIsLoading(false);
    };
  }, [user]);

  const value = {
    socket,
    isConnected,
    isLoading
  };

  return (
    <SocketContext.Provider value={value}>

      {children}

    </SocketContext.Provider>
  );
};