Begin script abstraction
This commit is contained in:
70
ReallifeGamemode.Server.Core/Main.cs
Normal file
70
ReallifeGamemode.Server.Core/Main.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ReallifeGamemode.Database.Models;
|
||||
using ReallifeGamemode.Server.Core.API;
|
||||
using ReallifeGamemode.Server.Core.Commands;
|
||||
using ReallifeGamemode.Server.Log;
|
||||
|
||||
namespace ReallifeGamemode.Server.Core
|
||||
{
|
||||
public class Main
|
||||
{
|
||||
internal static IAPI API { get; private set; }
|
||||
internal static Events.EventHandler EventHandler { get; private set; }
|
||||
|
||||
private static List<Script> loadedScripts = new List<Script>();
|
||||
|
||||
private readonly ILogger logger = LogManager.GetLogger<Main>();
|
||||
|
||||
public Main(IAPI api, Events.EventHandler eventHandler)
|
||||
{
|
||||
logger.LogInformation("Loading scripts...");
|
||||
API = api;
|
||||
EventHandler = eventHandler;
|
||||
|
||||
LoadScript();
|
||||
LoadCommands();
|
||||
}
|
||||
|
||||
private void LoadScript()
|
||||
{
|
||||
var allTypes = Assembly.GetExecutingAssembly().GetTypes();
|
||||
var commandTypes = allTypes.Where(t => t.IsSubclassOf(typeof(Script)) && !t.IsAbstract);
|
||||
|
||||
foreach (var scriptType in commandTypes)
|
||||
{
|
||||
logger.LogDebug("Loading script '{FullName}'", scriptType.FullName);
|
||||
var script = Activator.CreateInstance(scriptType) as Script;
|
||||
loadedScripts.Add(script);
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadCommands()
|
||||
{
|
||||
CommandHandler commandHandler = new CommandHandler(API);
|
||||
|
||||
var allTypes = Assembly.GetExecutingAssembly().GetTypes();
|
||||
var commandTypes = allTypes.Where(t => t.IsSubclassOf(typeof(Command)) && !t.IsAbstract);
|
||||
|
||||
foreach (var command in commandTypes)
|
||||
{
|
||||
var cmd = Activator.CreateInstance(command) as Command;
|
||||
commandHandler.RegisterCommand(cmd.CommandName, cmd);
|
||||
}
|
||||
}
|
||||
|
||||
public static DatabaseContext GetDbContext(bool useLoggerFactory = true)
|
||||
{
|
||||
return new DatabaseContext(useLoggerFactory ? LogManager.Factory : null);
|
||||
}
|
||||
|
||||
internal static TScript GetScript<TScript>() where TScript : Script
|
||||
{
|
||||
return loadedScripts.Where(s => s.GetType() == typeof(TScript)).First() as TScript;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user