-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprofile.js
188 lines (157 loc) · 6.14 KB
/
profile.js
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Assuming the token is stored in localStorage
const token = localStorage.getItem('access_token');
// Replace 'userId' with the current logged-in user's username, if stored
// Alternatively, fetch this from your backend if it's available there
const username = localStorage.getItem('username'); // Set this from your app's login or profile retrieval logic
// URLs for API endpoints (adjust according to actual API paths)
const apiMoodLogsUrl = 'http://127.0.0.1:8000/api/profile/moodlogs/';
const apiFriendsUrl = 'http://127.0.0.1:8000/api/profile/friends/';
const apiLeaderboardUrl = 'http://127.0.0.1:8000/api/profile/leaderboard/';
// Pagination variables
let currentPage = 1;
const itemsPerPage = 6;
let totalMoodLogs = [];
// Fetch and display mood logs
async function fetchMoodLogs() {
try {
const response = await fetch(apiMoodLogsUrl, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
});
totalMoodLogs = await response.json();
displayMoodLogs();
updatePaginationControls();
} catch (error) {
console.error('Error fetching mood logs:', error);
}
}
function displayMoodLogs() {
const moodLogsList = document.getElementById('moodLogsList');
moodLogsList.innerHTML = '';
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentPageLogs = totalMoodLogs.slice(startIndex, endIndex);
currentPageLogs.forEach(log => {
const moodBlock = document.createElement('div');
moodBlock.className = `mood-log-block mood-${log.mood_type.toLowerCase()}`;
const date = new Date(log.date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
moodBlock.innerHTML = `
<h3>${log.mood_type.charAt(0).toUpperCase() + log.mood_type.slice(1)}</h3>
<p>${date}</p>
<div class="mood-intensity">
${Array(5).fill().map((_, i) => `<span class="intensity-dot" style="opacity: ${i < log.intensity ? 1 : 0.3}"></span>`).join('')}
</div>
<p>${log.context}</p>
`;
moodLogsList.appendChild(moodBlock);
});
}
function updatePaginationControls() {
const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage');
const pageInfo = document.getElementById('pageInfo');
const totalPages = Math.ceil(totalMoodLogs.length / itemsPerPage);
prevPageBtn.disabled = currentPage === 1;
nextPageBtn.disabled = currentPage === totalPages;
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
}
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
displayMoodLogs();
updatePaginationControls();
}
});
document.getElementById('nextPage').addEventListener('click', () => {
const totalPages = Math.ceil(totalMoodLogs.length / itemsPerPage);
if (currentPage < totalPages) {
currentPage++;
displayMoodLogs();
updatePaginationControls();
}
});
// Fetch and display friends list
async function fetchFriends() {
try {
const response = await fetch(apiFriendsUrl, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
});
const data = await response.json();
const friendsList = document.getElementById('friendsList');
friendsList.innerHTML = '';
data.forEach(friend => {
const listItem = document.createElement('li');
listItem.textContent = friend.username;
friendsList.appendChild(listItem);
});
} catch (error) {
console.error('Error fetching friends:', error);
}
}
// Add a new friend
document.getElementById('addFriendBtn').addEventListener('click', async () => {
const friendUsername = document.getElementById('addFriendInput').value;
if (!friendUsername || !username) return;
try {
const response = await fetch(apiFriendsUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
friend_user: friendUsername // The username of the friend to add
})
});
if (response.ok) {
alert('Friend added successfully!');
fetchFriends();
} else {
alert('Error adding friend');
}
} catch (error) {
console.error('Error adding friend:', error);
}
});
// Fetch and display leaderboard
async function fetchLeaderboard() {
try {
const response = await fetch(apiLeaderboardUrl, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
});
const data = await response.json();
const leaderboardList = document.getElementById('leaderboardList');
leaderboardList.innerHTML = '';
data.forEach((user, index) => {
const listItem = document.createElement('li');
listItem.textContent = `${index + 1}. ${user.username} - ${user.score} points`;
leaderboardList.appendChild(listItem);
});
} catch (error) {
console.error('Error fetching leaderboard:', error);
}
}
// Mini-nav functionality
const miniNavButtons = document.querySelectorAll('.mini-nav-btn');
const contentSections = document.querySelectorAll('.content-section');
miniNavButtons.forEach(button => {
button.addEventListener('click', () => {
const target = button.dataset.target;
miniNavButtons.forEach(btn => btn.classList.remove('active'));
contentSections.forEach(section => section.classList.remove('active'));
button.classList.add('active');
document.getElementById(target).classList.add('active');
});
});
// Initialize by fetching all data
fetchMoodLogs();
fetchFriends();
fetchLeaderboard();