using System.Collections.Generic; using System.Collections.Immutable; using System.Transactions; using BlueWest.Collections; using MessagePack; namespace BlueWest.Data { [MessagePackObject] public class UserList: DataObject { [Key(9)] public readonly FastDictionary Users; public int Length = 0; public UserList(FastDictionary users) { Users = users; } private int GetIndexById(int userId) { var keys = Users.Keys; foreach (var key in keys) { if (key == userId) return key; } return -1; } internal DataQueryResult GetUserById(int id) { if (Users.ContainsKey(id)) return new PositiveResult(Users[id]); return new NegativeResult("Can't find a user with the provided id."); } internal bool RemoveUser(int userId) { if (Users.ContainsKey(userId)) { Users.Remove(userId); return true; } return false; } internal bool HasUser(int userId) { return Users.Contains(userId); } internal DataQueryResult UpdateUser(int userId, UserUpdateDto userUpdate) { Users[userId].Update(userUpdate); return Users[userId]; } internal bool UserHasTransaction(int userId, int transactionId) => HasUser(userId) && Users[userId].FinanceTransactions.Contains(transactionId); internal DataQueryResult GetTransactionById(int userId, int transactionId) { if(!HasUser(userId)) return new NegativeResult("Can't find a user with the provided id."); if (UserHasTransaction(userId, transactionId)) return new PositiveResult(Users[userId].FinanceTransactions[transactionId]); return new NegativeResult("No transaction was found with the specified id"); } internal User AddUser(int userId, UserUpdateDto userUpdateDto) { if (Users.ContainsKey(userId)) { Users[userId].Update(userUpdateDto); return Users[userId]; } var id = userId != -1 ? userId : Length + 1; var newUser = new User(userUpdateDto, id, new FastList()); Users.Add(Length, newUser); Length++; return newUser; } const string NoIdError = "No transaction was found with the specified id"; static NegativeResult NoIdResult = new NegativeResult(NoIdError); internal DataQueryResult AddFinanceTransaction(int userId, FinanceTransactionInsertDto financeTransactionDto) { if (Users.ContainsKey(userId)) { var financeTransaction = new FinanceTransaction(financeTransactionDto); Users[userId].AddTransaction(financeTransaction); return new PositiveResult(financeTransaction); } return NoIdResult; } internal FastList GetUserTransactions(int userId) { if (Users.ContainsKey(userId)) { return Users[userId].FinanceTransactions; } return new FastList(); } } }