using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace CtrEditor.FuncionesBase
{
    public class TagPattern
    {
        public const string DEFAULT_PATTERN = "DESCRIPCION";

        private static readonly Dictionary<string, string> _patternDescriptions = new Dictionary<string, string>
        {
            { "Descripcion", "First letter capitalized" },
            { "DESCRIPCION", "All uppercase text" },
            { "Siemens IO Input", "Format: Exxxxx.y (x: 0-65535, y: 0-7)" },
            { "Siemens IO Output", "Format: Axxxxx.y (x: 0-65535, y: 0-7)" },
            { "LETRASNUMEROS", "Format: ABC...123... (letters and numbers only, other chars become _)" },
            { "LETRASNUMEROS/*-+", "Format: ABC...123... (letters, numbers, and /*-+ chars only, other chars become _)" },
            { "LETRASNUMEROSESPACIOS", "Format: ABC...123... (letters, numbers and spaces only, other chars become _)" },
            { "LETRASNUMEROSESPACIOS/*-+", "Format: ABC...123... (letters, numbers, spaces, and /*-+ chars only, other chars become _)" },
            { "Numero", "Numeric value" }
        };

        public static List<string> GetPatternList()
        {
            return new List<string>(_patternDescriptions.Keys);
        }

        public static string ApplyPattern(string text, string pattern)
        {
            if (string.IsNullOrEmpty(text)) return text;

            return pattern switch
            {
                "Descripcion" => ApplyDescripcionPattern(text),
                "DESCRIPCION" => text.ToUpper(),
                "Siemens IO Input" => ApplySiemensPattern(text, "E"),
                "Siemens IO Output" => ApplySiemensPattern(text, "A"),
                "LETRASNUMEROS" => ApplyLetrasNumerosPattern(text),
                "LETRASNUMEROS/*-+" => ApplyLetrasNumerosSpecialPattern(text),
                "LETRASNUMEROSESPACIOS" => ApplyLetrasNumerosEspaciosPattern(text),
                "LETRASNUMEROSESPACIOS/*-+" => ApplyLetrasNumerosEspaciosSpecialPattern(text),
                "Numero" => ApplyNumberPattern(text),
                _ => text
            };
        }

        private static string ApplyDescripcionPattern(string text)
        {
            if (string.IsNullOrEmpty(text)) return text;
            return char.ToUpper(text[0]) + (text.Length > 1 ? text.Substring(1).ToLower() : "");
        }

        private static string ApplySiemensPattern(string text, string prefix)
        {
            var match = Regex.Match(text, $"{prefix}?(\\d{{1,5}})\\.?(\\d)?", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                int address = Math.Min(int.Parse(match.Groups[1].Value), 65535);
                int bit = match.Groups[2].Success ?
                    Math.Min(int.Parse(match.Groups[2].Value), 7) : 0;
                return $"{prefix}{address}.{bit}";
            }
            return $"{prefix}0.0"; // Default value if pattern doesn't match
        }

        private static string ApplyLetrasNumerosPattern(string text)
        {
            // Replace any character that is not a letter or digit with "_"
            char[] result = new char[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                if (char.IsLetter(text[i]) || char.IsDigit(text[i]))
                    result[i] = char.ToUpper(text[i]); // Convert letters to uppercase
                else
                    result[i] = '_';
            }

            return new string(result);
        }

        private static string ApplyLetrasNumerosEspaciosPattern(string text)
        {
            // Replace any character that is not a letter, digit, or space with "_"
            char[] result = new char[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                if (char.IsLetter(text[i]) || char.IsDigit(text[i]) || char.IsWhiteSpace(text[i]))
                    result[i] = char.ToUpper(text[i]); // Convert letters to uppercase
                else
                    result[i] = '_';
            }

            return new string(result);
        }

        private static string ApplyLetrasNumerosSpecialPattern(string text)
        {
            // Replace any character that is not a letter, digit, or one of /*-+ with "_"
            char[] result = new char[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                if (char.IsLetter(text[i]) || char.IsDigit(text[i]) || text[i] == '/' || text[i] == '*' || text[i] == '-' || text[i] == '+')
                    result[i] = char.ToUpper(text[i]); // Convert letters to uppercase
                else
                    result[i] = '_';
            }

            return new string(result);
        }

        private static string ApplyLetrasNumerosEspaciosSpecialPattern(string text)
        {
            // Replace any character that is not a letter, digit, space, or one of /*-+ with "_"
            char[] result = new char[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                if (char.IsLetter(text[i]) || char.IsDigit(text[i]) || char.IsWhiteSpace(text[i]) ||
                    text[i] == '/' || text[i] == '*' || text[i] == '-' || text[i] == '+')
                    result[i] = char.ToUpper(text[i]); // Convert letters to uppercase
                else
                    result[i] = '_';
            }

            return new string(result);
        }

        private static string ApplyNumberPattern(string text)
        {
            var match = Regex.Match(text, @"-?\d+\.?\d*");
            return match.Success ? match.Value : "0";
        }
    }

    public class TagPatternItemsSource<T> : IItemsSource
    {
        public ItemCollection GetValues()
        {
            ItemCollection items = new ItemCollection();
            foreach (string pattern in TagPattern.GetPatternList())
            {
                items.Add(pattern);
            }
            return items;
        }
    }
}