using ChatRoomContract;
using NLog;
using Bogus;
namespace ModeratorRest;
internal class Moderator
{
///
/// Logger for this class.
///
Logger log = LogManager.GetCurrentClassLogger();
///
/// Configures logging subsystem.
///
private void ConfigureLogging()
{
var config = new NLog.Config.LoggingConfiguration();
var console =
new NLog.Targets.ConsoleTarget("console")
{
Layout = @"${date:format=HH\:mm\:ss}|${level}| ${message} ${exception}"
};
config.AddTarget(console);
config.AddRuleForAllLevels(console);
LogManager.Configuration = config;
}
private void RunConnection(IChatRoomService chatRoom)
{
var faker = new Faker("en");
var name = faker.Name.FullName();
int clientId = chatRoom.RegisterClient(name);
log.Info($"Registered with client id {clientId}");
Console.Title = $"Moderator | {name} | {clientId}";
while (true)
{
var message = chatRoom.GetNewMessage();
if (message != null)
{
log.Info($"Checking message ({message.id}): {message.contents}");
Thread.Sleep(500);
if (message.needsToBeCensored)
{
chatRoom.RejectMessage(message.id);
}
else
{
chatRoom.ApproveMessage(message.id);
}
}
Thread.Sleep(1 * 1000);
}
}
private void Run()
{
ConfigureLogging();
while (true)
{
var client = new RestChatRoomClient("http://127.0.0.1:5001", new HttpClient());
try
{
RunConnection(client);
}
catch (Exception e)
{
//log whatever exception to console
log.Warn(e, "Unhandled exception caught. Will restart main loop.");
//prevent console spamming
Thread.Sleep(2000);
}
}
}
static void Main(string[] args)
{
var self = new Moderator();
self.Run();
}
}