using System; 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; [IgnoreMember] 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; } public DataQueryResult GetUserById(int id) { if (Users.ContainsKey(id)) return new DataQueryResult(Users[id], true); return new DataQueryResult(null, false, "Can't find a user with the provided id."); } public bool RemoveUser(int userId) { if (Users.ContainsKey(userId)) { Users.Remove(userId); return true; } return false; } internal bool HasUser(int userId) { return Users.Contains(userId); } public DataQueryResult UpdateUser(int userId, UserUpdateDto userUpdate) { if (Users.ContainsKey(userId)) { Users[userId].Update(userUpdate); return new DataQueryResult(Users[userId], true); } return new DataQueryResult(null, false); } internal bool UserHasTransaction(int userId, int transactionId) => HasUser(userId) && Users[userId].FinanceTransactions.Contains(transactionId); public DataQueryResult GetTransactionById(int userId, int transactionId) { if(!HasUser(userId)) return new DataQueryResult(new FinanceTransaction(), false, "Can't find a user with the provided id."); if (UserHasTransaction(userId, transactionId)) return new DataQueryResult(Users[userId].FinanceTransactions[transactionId]); return new DataQueryResult(new FinanceTransaction(), false, "Can't find a transaction with the provided id."); } public 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, DateTime.Now.TimeOfDay, new FastDictionary()); Users.Add(Length, newUser); Length++; return newUser; } const string NoIdError = "No transaction was found with the specified id"; public DataQueryResult AddFinanceTransaction(int userId, FinanceTransactionInsertDto financeTransactionDto) { if (Users.ContainsKey(userId)) { var now = TimeSpan.FromTicks(DateTime.Now.Ticks); var financeTransaction = new FinanceTransaction(financeTransactionDto, now, Users[userId].Id); Users[userId].AddTransaction(financeTransaction); return new DataQueryResult(financeTransaction); } return new DataQueryResult(new FinanceTransaction(), false, "no transaction with the provided id"); } public ImmutableArray GetUserTransactions(int userId) { if (Users.ContainsKey(userId)) { return Users[userId].FinanceTransactions.Values.ToImmutableArray(); } return new ImmutableArray(); } } }