using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Media;
namespace RuriLib.LS
{
///
/// Parse a command from LoliScript code.
///
public class CommandParser
{
///
/// The allowed command identifiers.
///
public enum CommandName
{
/// Prints some data to the log after replacing variables in it.
PRINT,
/// Sets the value of hidden variables.
SET,
/// Deletes variables.
DELETE,
/// Moves the mouse in a selenium-driven browser.
MOUSEACTION
}
///
/// Tests if a line is parsable as a command.
///
/// The data line to test
/// Whether the line contains a command or not
public static bool IsCommand(string line)
{
var groups = Regex.Match(line, @"^([^ ]*)").Groups;
return Enum.GetNames(typeof(CommandName)).Select(n => n.ToUpper()).Contains(groups[1].Value.ToUpper());
}
///
/// Gets a command Action from a command line.
///
/// The command line
/// The BotData needed for variable replacement
/// The Action that needs to be executed
public static Action Parse(string line, BotData data)
{
// Trim the line
var input = line.Trim();
// Return an exception if the line is empty
if (input == "") throw new ArgumentNullException();
var label = LineParser.ParseToken(ref input, TokenType.Label, false);
// Parse the identifier
var identifier = "";
try { identifier = LineParser.ParseToken(ref input, TokenType.Parameter, true); }
catch { throw new ArgumentException("Missing identifier"); }
switch ((CommandName)Enum.Parse(typeof(CommandName), identifier, true))
{
case CommandName.PRINT:
return new Action(() => data.Log(new LogEntry(BlockBase.ReplaceValues(input, data), Colors.White)));
case CommandName.SET:
return SetParser.Parse(input, data);
case CommandName.DELETE:
return DeleteParser.Parse(input, data);
case CommandName.MOUSEACTION:
return MouseActionParser.Parse(input, data);
default:
throw new ArgumentException($"Invalid identifier '{identifier}'");
}
}
}
}