File size: 2,078 Bytes
b681a44
 
 
 
 
cba7fd1
b681a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba7fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b681a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { createContext, useContext, useState } from 'react';

interface Message {
  id: number;
  text: string;
  translatedText?: string;
  isArabic?: boolean;
  isFrench?: boolean;
  timestamp: Date;
}

interface ChatContextType {
  messages: Message[];
  addMessage: (message: Message) => void;
}

const ChatContext = createContext<ChatContextType | undefined>(undefined);

export function ChatProvider({ children }: { children: React.ReactNode }) {
  const [messages, setMessages] = useState<Message[]>([]);

  const translateText = async (text: string, from: string, to: string) => {
    try {
      // Utilisation de l'API Google Translate via RapidAPI
      const response = await fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=' + from + '&tl=' + to + '&dt=t&q=' + encodeURI(text));
      
      if (!response.ok) {
        throw new Error('Translation failed');
      }

      const data = await response.json();
      // La traduction se trouve dans le premier élément du premier tableau
      const translatedText = data[0][0][0];
      
      return translatedText;
    } catch (error) {
      console.error('Translation error:', error);
      return text;
    }
  };

  const addMessage = async (message: Message) => {
    const from = message.isArabic ? 'ar' : 'fr';
    const to = message.isArabic ? 'fr' : 'ar';
    
    try {
      const translatedText = await translateText(message.text, from, to);
      
      const messageWithTranslation = {
        ...message,
        translatedText,
      };
      
      setMessages(prev => [...prev, messageWithTranslation]);
    } catch (error) {
      console.error('Error in message translation:', error);
      setMessages(prev => [...prev, message]);
    }
  };

  return (
    <ChatContext.Provider value={{ messages, addMessage }}>
      {children}
    </ChatContext.Provider>
  );
}

export function useChat() {
  const context = useContext(ChatContext);
  if (context === undefined) {
    throw new Error('useChat must be used within a ChatProvider');
  }
  return context;
}