File size: 5,490 Bytes
b405f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
document.addEventListener('DOMContentLoaded', () => {
    const chatbox = document.getElementById('chatbox');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    const clearMemoryBtn = document.getElementById('clearMemoryBtn'); // Get the new button

    // Function to append a message to the chatbox
    function appendMessage(sender, text) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('message', `${sender}-message`);

        const p = document.createElement('p');
        // Use textContent to avoid HTML injection
        p.textContent = text;

        messageElement.appendChild(p);
        chatbox.appendChild(messageElement);

        // Auto-scroll to the bottom
        chatbox.scrollTop = chatbox.scrollHeight;
    }

    // Function to send message to backend
    async function sendMessage() {
        const messageText = userInput.value.trim();
        if (messageText === "") {
            return; // Don't send empty messages
        }

        // Append user message to chatbox
        appendMessage('user', messageText);

        // Clear input and disable buttons
        userInput.value = '';
        userInput.disabled = true;
        sendBtn.disabled = true;
        if (clearMemoryBtn) clearMemoryBtn.disabled = true;


        // Optional: Add a loading indicator
        const loadingElement = document.createElement('div');
        loadingElement.classList.add('message', 'assistant-message', 'loading-indicator');
        loadingElement.textContent = 'AI is thinking...';
        chatbox.appendChild(loadingElement);
        chatbox.scrollTop = chatbox.scrollHeight; // Scroll to show indicator


        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message: messageText }),
            });

            // Remove loading indicator
            if (chatbox.contains(loadingElement)) {
                 chatbox.removeChild(loadingElement);
            }


            if (!response.ok) {
                 const errorData = await response.json().catch(() => ({})); // Try parsing JSON, fallback to empty object
                 const errorMessage = errorData.response || `Server returned status ${response.status}: ${response.statusText}`;
                 throw new Error(`Chat request failed: ${errorMessage}`);
            }

            const data = await response.json();
            appendMessage('assistant', data.response);

        } catch (error) {
            console.error('Error sending message:', error);
             // Remove loading indicator if still present
             if (chatbox.contains(loadingElement)) {
                 chatbox.removeChild(loadingElement);
             }
            appendMessage('assistant', `Error: Could not get a response. ${error.message}`);
        } finally {
            // Re-enable input and buttons
            userInput.disabled = false;
            sendBtn.disabled = false;
            if (clearMemoryBtn) clearMemoryBtn.disabled = false;
            userInput.focus(); // Put focus back on input field
        }
    }

     // Function to clear memory
    async function clearMemory() {
        if (confirm("Are you sure you want to clear the chat history? This will start a new conversation.")) {
             // Disable buttons during clear
             userInput.disabled = true;
             sendBtn.disabled = true;
             if (clearMemoryBtn) clearMemoryBtn.disabled = true;

             try {
                const response = await fetch('/clear_memory', {
                    method: 'POST',
                });

                if (!response.ok) {
                     const errorData = await response.json().catch(() => ({}));
                     const errorMessage = errorData.status || `Server returned status ${response.status}: ${response.statusText}`;
                    throw new Error(`Clear memory request failed: ${errorMessage}`);
                }

                // Clear the chatbox UI and add initial message
                chatbox.innerHTML = ''; // Clear all messages
                appendMessage('assistant', 'Chat history cleared. Starting a new conversation!');
                appendMessage('assistant', 'Hello! I\'m an AI chatbot with memory. How can I help you today?');


             } catch (error) {
                console.error('Error clearing memory:', error);
                appendMessage('assistant', `Error: Could not clear chat history. ${error.message}`);
             } finally {
                 // Re-enable buttons
                 userInput.disabled = false;
                 sendBtn.disabled = false;
                 if (clearMemoryBtn) clearMemoryBtn.disabled = false;
                 userInput.focus();
             }
        }
    }


    // Event listeners
    sendBtn.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault(); // Prevent newline in input
            sendMessage();
        }
    });

    // Add event listener for the clear memory button
    if (clearMemoryBtn) {
         clearMemoryBtn.addEventListener('click', clearMemory);
    }

    // Initial welcome message is already in index.html
});