using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BlueWest.Collections; using BlueWest.Core; using BlueWest.Data; using PerformanceSolution.Tools; namespace PerformanceSolution.Data { public static class MemoryData { public static UserList UserList = new UserList(new List()); private const string SavePathName = "userData"; private static bool DEBUG = true; static MemoryData() { if (DEBUG) { UserList = GenerateMockData(); SaveUserList(); } LoadUsers(); } public static void SaveUserList(UserList userList) { UserList = userList; SaveLoadManager.Save(UserList, SavePathName); } public static void LoadUsers() { UserList = SaveLoadManager.Load(SavePathName); UserList ??= new UserList(new List()); } public static User? GetUserById(int id) { var user = UserList.Users.FirstOrDefault(user => user.Id == id); //var d = new UserUpdateDto(user); return user; } public static bool RemoveUser(int userId) { int index = GetIndexById(userId); if (index == -1) return false; UserList.Users.RemoveAt(index); SaveUserList(); return true; } public static async Task AddUserAsync(User user) => await Task.Run(() => { AddOrModifyUser(user); }); private static int GetIndexById(int userId) => UserList.Users.FindIndex(row => row.Id == userId); private static void SaveUserList() => SaveUserList(UserList); public static void AddOrModifyUser(User user) { var index = GetIndexById(user.Id); if (index != -1) { UserList.Users[index] = user; SaveUserList(); } else { UserList.Users.Add(user); SaveUserList(); } } public static User? AddOrModifyUser(UserUpdateDto userUpdateDto, int userId = -1) { var id = userId != -1 ? userId : UserList.Length + 1; var index = GetIndexById(userId); User? user; if (index != -1) { user = GetUserById(id); if (user == null) return user; UserList.Users[index] = user; SaveUserList(); } else { user = new User(userUpdateDto); UserList.Users.Add(user); SaveUserList(); } return user; } public static User? UpdateUser(int userId, UserUpdateDto userUpdate) { var index = GetIndexById(userId); if (index == -1) return null; var actualUser = GetUserById(userId); if (actualUser == null) return null; actualUser.Update(userUpdate); UserList.Users[index] = actualUser; SaveUserList(); return actualUser; } public static FinanceTransaction? AddFinanceTransaction(int userId, FinanceTransaction financeTransaction) { var user = GetUserById(userId); if (user == null) return null; user.AddTransaction(financeTransaction); SaveUserList(); return financeTransaction; } private static UserList GenerateMockData() { var u = new User(1, "Rui Sousa", "Sagres", "NOADD", "NOADD", 0 , 0, new List() { new FinanceTransaction(0, 1, FinanceTransactionType.Buy, FinanceSymbol.BTC_EUR, 0, 0, 0.1, DateTime.Now) }); var list = new List(10); list.Add(u); return new UserList(list); } } }