using System.Text.RegularExpressions;

using Forwarder.Models;
using Forwarder.Services.Implementations.MessageConverters;

namespace Forwarder.Services.Implementations;

/// <inheritdoc />
public partial class MessageConverterService : IMessageConverterService
{
	private readonly IEnumerable<IMessageConverter> _converters = [
		new SurGardVersion4MessageConverter(),
		new Ademco685MessageConverter(),
	];

	// Словарь для сопоставления символов с их именами
	private static readonly Dictionary<char, string> ControlCharNames = new()
	{
		{ '\u0000', "" },
		{ '\u0001', "[SOH]" },
		{ '\u0002', "[STX]" },
		{ '\u0003', "[ETX]" },
		{ '\u0004', "[EOT]" },
		{ '\u0005', "[ENQ]" },
		{ '\u0006', "[ACK]" },
		{ '\u0007', "[BEL]" },
		{ '\u0008', "[BS]" },
		{ '\u0009', "[TAB]" },
		{ '\u000A', "[LF]" },
		{ '\u000B', "[VT]" },
		{ '\u000C', "[FF]" },
		{ '\u000D', "[CR]" },
		{ '\u000E', "[SO]" },
		{ '\u000F', "[SI]" },
		{ '\u0010', "[DLE]" },
		{ '\u0011', "[DC1]" },
		{ '\u0012', "[DC2]" },
		{ '\u0013', "[DC3]" },
		{ '\u0014', "[DC4]" },
		{ '\u0015', "[NAK]" },
		{ '\u0016', "[SYN]" },
		{ '\u0017', "[ETB]" },
		{ '\u0018', "[CAN]" },
		{ '\u0019', "[EM]" },
		{ '\u001A', "[SUB]" },
		{ '\u001B', "[ESC]" },
		{ '\u001C', "[FS]" },
		{ '\u001D', "[GS]" },
		{ '\u001E', "[RS]" },
		{ '\u001F', "[US]" }
	};

	/// <inheritdoc />    
	public Result<IMessageConverter> FindMessageConverter(string messageText)
	{
		var converter = _converters.FirstOrDefault(x => x.CanHandle(messageText));
		if (converter is null)
		{
			return "Converter is not found";
		}

		return Result<IMessageConverter>.Success(converter);
	}

	/// <inheritdoc />
	public string FormatMessage(string input)
	{
		// Используем регулярное выражение для поиска и замены
		return AsciiSymbols().Replace(input, match =>
		{
			var controlChar = match.Value[0];
			return ControlCharNames.TryGetValue(controlChar, out var value) ? value : match.Value;
		});
	}

	[GeneratedRegex(@"[\x00-\x1F]")]
	private static partial Regex AsciiSymbols();
}