using MongoDB.Driver; using Supercell.GUT.Server.Database; using Supercell.GUT.Server.Database.Document; using Supercell.GUT.Server.Util; using Supercell.GUT.Titan.Logic.Math; namespace Supercell.GUT.Server.Document; internal class DocumentManager { private const string AccountCollectionName = "t_account_info"; private const string AvatarCollectionName = "t_player_avatar"; private const string AccountIdCounterName = "AccountId"; private readonly DatabaseManager _databaseManager; public LogicLong Id { get; private set; } = new(); public AccountDocument? AccountDocument { get; private set; } public AvatarDocument? AvatarDocument { get; private set; } public DocumentManager(DatabaseManager databaseManager) { _databaseManager = databaseManager; } public async Task SaveAsync() { if (AccountDocument != null) { IMongoCollection accountCollection = _databaseManager.GetCollection(AccountCollectionName); await accountCollection.ReplaceOneAsync(doc => doc.DocumentId.Equals(AccountDocument.DocumentId), AccountDocument); } if (AvatarDocument != null) { AvatarDocument.LastSaveTime = TimeUtil.GetCurrentTimestamp(); IMongoCollection avatarCollection = _databaseManager.GetCollection(AvatarCollectionName); await avatarCollection.ReplaceOneAsync(doc => doc.DocumentId.Equals(AvatarDocument.DocumentId), AvatarDocument); } } public async Task CreateAccount() { if (AccountDocument != null) throw new InvalidOperationException("DocumentManager::CreateAccount: called when AccountDocument already created!"); int lowId = await _databaseManager.GetNextLowIdAsync(AccountIdCounterName); AccountDocument = new(new(0, lowId), "ToDoRandomToken"); IMongoCollection accountCollection = _databaseManager.GetCollection(AccountCollectionName); await accountCollection.InsertOneAsync(AccountDocument); Id = AccountDocument.DocumentId; } public async Task EnsureAccountDocument() { if (AccountDocument != null) return; IMongoCollection accountCollection = _databaseManager.GetCollection(AccountCollectionName); AccountDocument = await (await accountCollection.FindAsync(document => document.DocumentId.Equals(Id))).SingleOrDefaultAsync(); } public async Task EnsureAvatarDocument() { if (AvatarDocument != null) return; IMongoCollection avatarCollection = _databaseManager.GetCollection(AvatarCollectionName); AvatarDocument = await (await avatarCollection.FindAsync(document => document.DocumentId.Equals(Id))).SingleOrDefaultAsync(); if (AvatarDocument == null) { AvatarDocument = new(Id); await avatarCollection.InsertOneAsync(AvatarDocument); } } public void SetDocumentId(LogicLong id) { if (Id.LowerInt > 0) throw new InvalidOperationException("DocumentManager::SetDocumentId: trying to override Id."); Id = id; } }