bib_Talk_Chatprogramm/bibtalk/bib-talk/Repository/MainWindowDatabase.cs
BlackViron 068ba16156 3 Schichten Model
3 Schichten Model umgesetzt
2024-07-01 16:21:03 +02:00

97 lines
3.5 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace bib_talk.Repository
{
public class MainWindowDatabase
{
MainWindow mainWindow;
public MainWindowDatabase(MainWindow mainWindow)
{
this.mainWindow = mainWindow;
}
public async void SendMessage()
{
if (!string.IsNullOrEmpty(mainWindow.messageBOX.Text))
{
var message = new MessageDto
{
Username = mainWindow.loggedinUser,
Message = mainWindow.messageBOX.Text,
Timestamp = DateTime.Now,
};
using (var client = new HttpClient())
{
var json = JsonConvert.SerializeObject(message);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://daddypig.dns.navy:5114/api/messages/send", content);
if (response.IsSuccessStatusCode)
{
mainWindow.messageBOX.Clear();
LoadMessages(); // Reload messages after sending
}
}
}
}
public async void LoadMessages()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("http://daddypig.dns.navy:5114/api/messages/get");
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<List<Message>>(responseContent);
mainWindow.chatlistbox.ItemsSource = messages;
if (mainWindow.chatlistbox.Items.Count > 0)
{
var lastItem = mainWindow.chatlistbox.Items[mainWindow.chatlistbox.Items.Count - 1];
mainWindow.chatlistbox.ScrollIntoView(lastItem);
}
}
}
}
public async void LoadOnlineUsers()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("http://daddypig.dns.navy:5114/api/users/online-users");
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var onlineUsers = JsonConvert.DeserializeObject<List<User>>(responseContent);
mainWindow.onlineUsersListBox.ItemsSource = onlineUsers;
}
}
}
public async void LogoutUser()
{
using (var client = new HttpClient())
{
var logoutData = new { Username = mainWindow.loggedinUser, Password = "", Email = "", Birthday = "", IsOnline = "" };
var json = JsonConvert.SerializeObject(logoutData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://daddypig.dns.navy:5114/api/users/logout", content);
var responseContent = await response.Content.ReadAsStringAsync();
mainWindow.Close();
}
}
}
}