CodeLiturgy.Dashboard/BlueWest.Data/UserList.cs

125 lines
3.4 KiB
C#

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<int, User> Users;
[IgnoreMember] public int Length = 0;
public UserList(FastDictionary<int, User> 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 User GetUserById(int id)
{
if (Users.ContainsKey(id)) return Users[id];
return new User();
}
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 User UpdateUser(int userId, UserUpdateDto userUpdate)
{
if (Users.ContainsKey(userId))
{
Users[userId].Update(userUpdate);
return Users[userId];
}
return new User();
}
internal bool UserHasTransaction(int userId, int transactionId) => HasUser(userId) && Users[userId].FinanceTransactions.Contains(transactionId);
public FinanceTransaction GetTransactionById(int userId, int transactionId)
{
if(!HasUser(userId)) return new FinanceTransaction();
if (UserHasTransaction(userId, transactionId)) return Users[userId].FinanceTransactions[transactionId];
return new FinanceTransaction();
}
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<int, FinanceTransaction>());
Users.Add(Length, newUser);
Length++;
return newUser;
}
const string NoIdError = "No transaction was found with the specified id";
public FinanceTransaction 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 financeTransaction;
}
return new FinanceTransaction();
}
public ImmutableArray<FinanceTransaction> GetUserTransactions(int userId)
{
if (Users.ContainsKey(userId))
{
return Users[userId].FinanceTransactions.Values.ToImmutableArray();
}
return new ImmutableArray<FinanceTransaction>();
}
}
}