using ChatRoomContract;
using NLog;
using Bogus;
namespace Participant;
internal class Participant
{
///
/// 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 rnd = new Random();
var name = faker.Name.FullName();
int clientId = chatRoom.RegisterClient(name);
log.Info($"Registered with client id {clientId}");
while (true)
{
int strikes = chatRoom.GetStrikes(clientId);
Console.Title = $"Participant | {name} | {clientId} | {strikes} Strikes";
var message = string.Join(" ", faker.Lorem.Words(5));
bool needsToBeCensored = rnd.Next(0, 100) > 50;
if (chatRoom.SendMessage(clientId, message, needsToBeCensored)) {
log.Info("Sent message");
} else {
log.Info("Failed to send message, blocked");
var blockedUntil = chatRoom.GetBlockedUntil(clientId);
var now = DateTime.UtcNow;
if (blockedUntil != null && blockedUntil > now)
{
var delta = blockedUntil.Value - now;
log.Info($"Waiting {delta.TotalSeconds:F3}s until block expires");
Thread.Sleep((int)delta.TotalMilliseconds);
}
}
Thread.Sleep(2 * 1000);
}
}
private void Run()
{
ConfigureLogging();
while (true)
{
var client = new ChatRoomClient("http://127.0.0.1:5000");
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 Participant();
self.Run();
}
}