using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace RuriLib
{
///
/// The condition on which to base the outcome of a comparison.
///
public enum Condition
{
/// A is less than B.
LessThan,
/// A is greater than B.
GreaterThan,
/// A is equal to B.
EqualTo,
/// A is not equal to B.
NotEqualTo,
/// A contains B.
Contains,
/// A does not contain B.
DoesNotContain,
/// Whether any variable can be replaced inside the string.
Exists,
/// Whether no variable can be replaced inside the string.
DoesNotExist,
/// A matches regex pattern B.
MatchesRegex,
/// A does not match regex pattern B.
DoesNotMatchRegex
}
///
/// Static Class used to check if a condition is true or false.
///
public static class ConditionChecker
{
///
/// Verifies if a comparison is true or false.
///
/// The left-hand term in the comparison
/// The condition of the comparison
/// The right-hand term in the comparison
/// The BotData used for variable replacement
/// Whether the comparison is true or false
public static bool Verify(string left, Condition condition, string right, BotData data)
{
var style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; // Needed when comparing values with a currency symbol
var provider = new CultureInfo("en-US");
var L = BlockBase.ReplaceValuesRecursive(left, data); // The left-hand term can accept recursive values like
var r = BlockBase.ReplaceValues(right, data); // The right-hand term cannot
switch (condition)
{
case Condition.EqualTo:
return L.Any(l => l == r);
case Condition.NotEqualTo:
return L.Any(l => l != r);
case Condition.GreaterThan:
return L.Any(l => decimal.Parse(l.Replace(',', '.'), style, provider) > decimal.Parse(r, style, provider));
case Condition.LessThan:
return L.Any(l => decimal.Parse(l.Replace(',', '.'), style, provider) < decimal.Parse(r, style, provider));
case Condition.Contains:
return L.Any(l => l.Contains(r));
case Condition.DoesNotContain:
return L.Any(l => !l.Contains(r));
case Condition.Exists:
return L.Any(l => l != left); // Returns true if any replacement took place
case Condition.DoesNotExist:
return L.All(l => l == left); // Returns true if no replacement took place
case Condition.MatchesRegex:
return L.Any(l => Regex.Match(l, r).Success);
case Condition.DoesNotMatchRegex:
return L.Any(l => !Regex.Match(l, r).Success);
default:
return false;
}
}
}
}