using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Mapster; using MongoDB.Bson; using MongoDB.Driver; using PhoenixLib.Logging; using Plugin.MongoLogs.Entities; namespace Plugin.MongoLogs.Utils { internal static class MongoDatabaseHelper { public static async Task InsertLogAsync(this IMongoDatabase database, T log) { IMongoCollection collection = database.GetCollection(MongoHelper.CollectionName); if (MongoHelper.EntityType == null) { await collection.InsertOneAsync(log.ToBsonDocument()); return; } var document = log.Adapt(typeof(T), MongoHelper.EntityType).ToBsonDocument(); document.Remove("_t"); await collection.InsertOneAsync(document); } private static class MongoHelper { static MongoHelper() { Type entityType = typeof(MongoHelper).Assembly.GetTypes() .FirstOrDefault(s => typeof(IPlayerLogEntity).IsAssignableFrom(s) && s.GetCustomAttribute()?.MessageType == typeof(T)); CollectionName = "NOT_HANDLED_PLZ_DEVS_WTF"; if (entityType == null) { Log.Warn($"{typeof(T)} has no mappable entity"); return; } EntityType = entityType; string collectionNameAttribute = entityType.GetCustomAttribute()?.CollectionName; if (collectionNameAttribute == null) { Log.Warn($"{typeof(T)} has no defined collection"); return; } CollectionName = collectionNameAttribute; } internal static string CollectionName { get; } internal static Type EntityType { get; } } } }