TBConsole/TBConsole/TBConsoleMod.cs

83 lines
No EOL
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using IllusionPlugin;
using TechbloxModdingAPI.Commands;
using UnityEngine;
namespace TBConsole
{
public class TBConsoleMod : IEnhancedPlugin
{
public override string Name => "TBConsole";
public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
private WebServer _server;
private UnityLogHandler _logHandler;
public override void OnApplicationStart()
{
TechbloxModdingAPI.Main.Init();
_server = new WebServer(CommandReceived);
_server.Start();
}
private async Task<string> CommandReceived(string command)
{
if (_logHandler == null)
Debug.unityLogger.logHandler = _logHandler = new UnityLogHandler(Debug.unityLogger.logHandler);
var logTask = _logHandler.CollectLogMessages();
bool inString = false;
var cmdparts = new List<string>();
command = command.Trim();
int lastIndex = 0;
for (int i = 0; i <= command.Length; i++)
{
if (i < command.Length && command[i] == '"') inString = !inString;
else if (!inString && (i == command.Length || command[i] == ' '))
{
cmdparts.Add(command.Substring(lastIndex, i - lastIndex).Trim('"'));
lastIndex = i + 1;
}
}
//Console.WriteLine("Command parts: " + cmdparts.Aggregate((a, b) => a + ", " + b));
switch (cmdparts.Count)
{
case 1:
ExistingCommands.Call(cmdparts[0]);
break;
case 2:
ExistingCommands.Call(cmdparts[0], cmdparts[1]);
break;
case 3:
ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2]);
break;
case 4:
ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2], cmdparts[3]);
break;
default:
return "Too many arguments! Maximum for default commands is 3";
}
string result = await logTask;
return $"Got it: {command}\n{result}";
}
public override void OnApplicationQuit()
{
_server.Stop();
TechbloxModdingAPI.Main.Shutdown();
}
public static void Main(string[] args)
{
var mod = new TBConsoleMod();
mod._server = new WebServer(mod.CommandReceived);
mod._server.Start();
Console.ReadLine();
}
}
}