RegexBot/Module/VoteTempChannel/VotingSession.cs

88 lines
2.5 KiB
C#
Raw Normal View History

2018-10-29 01:39:48 +00:00
using System;
using System.Collections.Generic;
namespace Noikoio.RegexBot.Module.VoteTempChannel
{
/// <summary>
2018-10-29 02:37:07 +00:00
/// Keeps information on voting sessions and cooldowns.
2018-10-29 01:39:48 +00:00
/// </summary>
class VotingSession
{
private Configuration _conf;
private DateTimeOffset _initialVoteTime;
private List<ulong> _votes;
2018-10-29 02:37:07 +00:00
public DateTimeOffset? _cooldownStart;
2018-10-29 01:39:48 +00:00
2018-10-31 20:11:12 +00:00
public VotingSession(Configuration conf)
2018-10-29 01:39:48 +00:00
{
2018-10-31 20:11:12 +00:00
_conf = conf;
2018-10-29 02:37:07 +00:00
_cooldownStart = null;
2018-10-29 01:39:48 +00:00
_votes = new List<ulong>();
}
/// <summary>
/// Counts a user vote.
/// </summary>
/// <returns>False if the user already has a vote counted.</returns>
public bool AddVote(ulong id, out int voteCount)
2018-10-29 01:39:48 +00:00
{
// Mark the start of a new session, if applicable.
if (_votes.Count == 0) _initialVoteTime = DateTimeOffset.UtcNow;
if (_votes.Contains(id))
{
voteCount = -1;
return false;
}
2018-10-29 01:39:48 +00:00
_votes.Add(id);
voteCount = _votes.Count;
2018-10-29 01:39:48 +00:00
return true;
}
2018-10-31 21:29:08 +00:00
/// <summary>
/// Reports if this session is awaiting its first vote.
/// </summary>
public bool AwaitingInitialVote()
{
if (IsInCooldown()) return false;
return _votes.Count == 0;
}
2018-10-29 01:39:48 +00:00
/// <summary>
/// Checks if the voting session has expired.
2018-10-29 02:37:07 +00:00
/// To be called by the background task. This automatically resets and sets cooldown.
2018-10-29 01:39:48 +00:00
/// </summary>
public bool IsSessionExpired()
{
if (_votes.Count == 0) return false;
if (DateTimeOffset.UtcNow > _initialVoteTime + _conf.VotingDuration)
{
// Clear votes. And because we're clearing it due to an expiration, set a cooldown.
Reset();
StartCooldown();
return true;
}
return false;
}
public void StartCooldown()
{
2018-10-29 02:37:07 +00:00
_cooldownStart = DateTimeOffset.UtcNow;
2018-10-29 01:39:48 +00:00
}
public bool IsInCooldown()
{
2018-10-29 02:37:07 +00:00
if (!_cooldownStart.HasValue) return false;
return _cooldownStart.Value + _conf.VotingCooldown > DateTimeOffset.UtcNow;
2018-10-29 01:39:48 +00:00
}
/// <summary>
/// Resets the object to its initial state.
/// </summary>
public void Reset()
{
_votes.Clear();
2018-10-29 02:37:07 +00:00
_cooldownStart = null;
2018-10-29 01:39:48 +00:00
}
}
}