using System.Drawing;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;

namespace CAD2XMAL
{
    internal class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new();
            StringBuilder sbRaw = new();
            //string path = string.Empty;
            using StreamReader sr = new(@"E:\Test.txt");
            string s = sr.ReadToEnd();

            string[] t1 = s.Split("\r\n");
            Console.Clear();

            Dictionary<RectangleF, DrawData> RecButton = [];
            Dictionary<RectangleF, DrawData> CirButton = [];
            Dictionary<RectangleF, DrawData> RecBorder = [];
            Dictionary<RectangleF, DrawData> CirBorder = [];
            List<DrawLine> Line = [];
            HashSet<string> Names = [];
            string strock = "#000000";
            string pathStart1 = string.Empty;
            string pathStart2 = string.Empty;
            string geo = string.Empty;
            string pathEnd1 = string.Empty;
            string pathEnd2 = string.Empty;


            foreach (var item in t1)
            {
                if (item.Contains("<TextBlock") || item.Contains("<Span") || item.Contains("</TextBlock>"))
                {
                    sb.AppendLine(item);
                }
                if (item.Contains("Stroke"))
                {
                    string temp = item.Substring(item.IndexOf("Stroke=\""));
                    string[] color = temp.Split("\"");
                    strock = color[1];
                }

                switch (item)
                {
                    case string sx when sx.Contains("<Path "):
                        pathStart1 = item.Trim();
                        break;
                    case string sx when sx.Contains("<Path.Data>"):
                        pathStart2 = item.Trim();
                        break;
                    case string sx when sx.Contains("</Path.Data>"):
                        pathEnd1 = item.Trim();
                        break;
                    case string sx when sx.Contains("</Path>"):
                        if (string.IsNullOrEmpty(geo))
                            break;

                        pathEnd2 = item.Trim();
                        sbRaw.AppendLine(pathStart1);
                        sbRaw.AppendLine(pathStart2);
                        sbRaw.AppendLine(geo);
                        sbRaw.AppendLine(pathEnd1);
                        sbRaw.AppendLine(pathEnd2);
                        geo = string.Empty;
                        break;
                    default:
                        break;
                }

                if (!item.Contains("PathGeometry"))
                    continue;

                string[] test = item.Split('"');
                test = test[1].Split(" ");

                switch (test.Length)
                {
                    case 6:
                        {

                            string X1 = test[1];
                            string Y1 = test[2];
                            string X2 = test[4];
                            string Y2 = test[5];
                            Line.Add(new(X1, Y1, X2, Y2, strock));
                            break;
                        }

                    case 16:
                        {
                            float dx1 = Convert.ToSingle(test[4]);
                            float dy1 = Convert.ToSingle(test[5]);

                            float dx2 = Convert.ToSingle(test[7]);
                            float dy2 = Convert.ToSingle(test[8]);

                            float dx3 = Convert.ToSingle(test[10]);
                            float dy3 = Convert.ToSingle(test[11]);

                            float dx4 = Convert.ToSingle(test[13]);
                            float dy4 = Convert.ToSingle(test[14]);

                            float[] dx = [dx1, dx2, dx3, dx4];
                            float[] dy = [dy1, dy2, dy3, dy4];
                            float width = dx.Max() - dx.Min();
                            float height = dy.Max() - dy.Min();
                            float left = dx.Min();
                            float top = dy.Min();

                            if (width > 120 && height > 120)
                                RecBorder.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                            else
                                RecButton.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                        }
                        break;
                    case 22:
                        {

                            float dStart = Convert.ToSingle(test[1]);
                            float dCenter = Convert.ToSingle(test[2]);
                            float dr = Convert.ToSingle(test[4]);
                            float width = dr * 2;
                            float height = dr * 2;
                            float left = dStart - (dr * 2);
                            float top = dCenter - dr;
                            switch (dr)
                            {
                                case > 15:
                                    CirButton.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                                    break;

                                default:
                                    //Console.WriteLine($"<Border BorderBrush=\"Black\" Width=\"{dr * 2}\" Height=\"{dr * 2}\" CornerRadius=\"{dr * 2}\" BorderThickness=\"1\" Canvas.Left=\"{dStart - (dr * 2)}\" Canvas.Top=\"{dCenter - dr}\"/>");
                                    CirBorder.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                                    break;
                            }

                        }
                        break;

                    default:
                        geo = item.Trim();
                        break;
                }


            }


            using StreamReader sr3 = new(@"E:\Test3.txt");
            string s2 = sr3.ReadToEnd();

            string[] t3 = s2.Split("\r\n");

            foreach (var item in t3)
            {
                if (item.Contains("<TextBlock") || item.Contains("<Span") || item.Contains("</TextBlock>"))
                {
                    sb.AppendLine(item);
                }

                if (item.Contains("Stroke"))
                {
                    string temp = item.Substring(item.IndexOf("Stroke=\""));
                    string[] color = temp.Split("\"");
                    strock = color[1];
                }

                switch (item)
                {
                    case string sx when sx.Contains("<Path "):
                        pathStart1 = item.Trim();
                        break;
                    case string sx when sx.Contains("<Path.Data>"):
                        pathStart2 = item.Trim();
                        break;
                    case string sx when sx.Contains("</Path.Data>"):
                        pathEnd1 = item.Trim();
                        break;
                    case string sx when sx.Contains("</Path>"):
                        if (string.IsNullOrEmpty(geo))
                            break;

                        pathEnd2 = item.Trim();
                        sbRaw.AppendLine(pathStart1);
                        sbRaw.AppendLine(pathStart2);
                        sbRaw.AppendLine(geo);
                        sbRaw.AppendLine(pathEnd1);
                        sbRaw.AppendLine(pathEnd2);
                        geo = string.Empty;
                        break;
                    default:
                        break;
                }

                if (!item.Contains("PathGeometry"))
                    continue;

                string[] test = item.Split('"');
                test = test[1].Split(" ");

                switch (test.Length)
                {
                    case 6:
                        string X1 = test[1];
                        string Y1 = test[2];
                        string X2 = test[4];
                        string Y2 = test[5];
                        Line.Add(new(X1, Y1, X2, Y2, strock));
                        break;

                    case 8:
                        break;
                    case 11:
                        break;
                    case 15:
                        break;

                    case 16:
                        {
                            float dx1 = Convert.ToSingle(test[4]);
                            float dy1 = Convert.ToSingle(test[5]);

                            float dx2 = Convert.ToSingle(test[7]);
                            float dy2 = Convert.ToSingle(test[8]);

                            float dx3 = Convert.ToSingle(test[10]);
                            float dy3 = Convert.ToSingle(test[11]);

                            float dx4 = Convert.ToSingle(test[13]);
                            float dy4 = Convert.ToSingle(test[14]);

                            float[] dx = [dx1, dx2, dx3, dx4];
                            float[] dy = [dy1, dy2, dy3, dy4];
                            float width = dx.Max() - dx.Min();
                            float height = dy.Max() - dy.Min();
                            float left = dx.Min();
                            float top = dy.Min();

                            if (height > 150)
                                RecBorder.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                            else
                                RecButton.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                        }
                        break;
                    case 22:
                        {

                            float dStart = Convert.ToSingle(test[1]);
                            float dCenter = Convert.ToSingle(test[2]);
                            float dr = Convert.ToSingle(test[4]);
                            float width = dr * 2;
                            float height = dr * 2;
                            float left = dStart - (dr * 2);
                            float top = dCenter - dr;
                            switch (dr)
                            {
                                case > 15:
                                    CirButton.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                                    break;

                                default:
                                    CirBorder.TryAdd(new RectangleF(left, top, width, height), new(width, height, left, top, strock));
                                    break;
                            }

                        }
                        break;

                    default:
                        geo = item.Trim();
                        break;
                }


            }

            foreach (var item in CirButton)
            {
                foreach (var cb in CirButton)
                {
                    if (cb.Key.Contains((float)item.Value.Left, (float)item.Value.Top) && cb.Value != item.Value)
                    {
                        CirBorder.Add(cb.Key, cb.Value);
                        CirBorder.Add(item.Key, item.Value);
                    }
                }
            }
            foreach (var item in CirBorder.Keys)
            {
                if (!CirButton.ContainsKey(item))
                    continue;

                CirButton.Remove(item);
            }

            using StreamReader sr2 = new(@"E:\Test2.txt");
            string text = sr2.ReadToEnd();
            sb.AppendLine(text);
            string[] t2 = sb.ToString().Split("</TextBlock>");

            Console.WriteLine("<Canvas x:Name=\"Text\">");

            foreach (var item in t2)
            {

                if (!item.Contains("<TextBlock"))
                    continue;

                string[] te = item.Trim().Replace("\r\n", string.Empty).Split('>');
                string[] content1 = te[0].Split("\"");
                float strLeft = Convert.ToSingle(content1[7]);
                float strTop = Convert.ToSingle(content1[9]) + 20;
                float fontsize = Convert.ToSingle(content1[1]);
                string foreground = content1[5];
                string str = te[2].Trim().Split('<')[0];
                if (str.Contains("slm") || str.Contains("0.0"))
                    continue;
                if (fontsize == 0f)
                    fontsize = 30;
                foreach (var recb in RecButton)
                {
                    if (!recb.Key.Contains(strLeft, strTop))
                        continue;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Content = str;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Foreground = foreground;
                    goto End;
                }

                foreach (var recb in CirButton)
                {
                    if (!recb.Key.Contains(strLeft, strTop))
                        continue;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Content = str;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Foreground = foreground;
                    goto End;

                }

                //foreach (var recb in RecBorder)
                //{
                //    if (!recb.Key.Contains(strLeft, strTop))
                //        continue;
                //    recb.Value.Fontsize = fontsize;
                //    recb.Value.Content = str;
                //    recb.Value.Fontsize = fontsize;
                //    recb.Value.Foreground = foreground;
                //    goto End;
                //}

                foreach (var recb in CirBorder)
                {
                    if (!recb.Key.Contains(strLeft, strTop + 70))
                        continue;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Content = str;
                    recb.Value.Fontsize = fontsize;
                    recb.Value.Foreground = foreground;
                    break;
                }
                Console.WriteLine($"<TextBlock Text=\"{str}\" FontSize=\"32\" Foreground=\"{foreground}\" Canvas.Left=\"{strLeft:0}\" Canvas.Top=\"{strTop:0}\" />");

            End:
                continue;
            }


            Console.WriteLine("</Canvas>");
            Console.WriteLine();

            int noName = 0;
            Console.WriteLine("<Canvas x:Name=\"RecButton\" Panel.ZIndex=\"1\">");
            foreach (var item in RecButton)
            {
                var value = item.Value;

                string name = string.IsNullOrEmpty(value.Content) ? $"NoName_{noName++}" : value.Content;
                name = name.Replace(" ", "");
                name = name.Replace("-", "");
                name = name.Replace(".", "");

                int innerLines = Line.Where(t => item.Key.Contains((Convert.ToSingle(t.X1) + Convert.ToSingle(t.X2)) / 2, (Convert.ToSingle(t.Y1) + Convert.ToSingle(t.Y2)) / 2)).Count();
                string baseName = innerLines switch
                {
                    >= 2 => "MFC",
                    _ => "RBU_"
                };
                if (int.TryParse(name, out _))
                {
                    for (int i = 1; ; i++)
                    {
                        if (Names.Add(name))
                            break;

                        if (Names.Add($"{name}_{i}"))
                        {
                            name = $"{name}_{i}";
                            break;
                        }
                    }
                    Console.WriteLine($"<Button x:Name=\"{baseName}{name}\" Width=\"{value.Width:0}\" Height=\"{value.Height:0}\" Canvas.Left=\"{value.Left}\" Canvas.Top=\"{value.Top:0}\" BorderBrush=\"{value.Strock}\" Background=\"Transparent\" Panel.ZIndex=\"1\" BorderThickness=\"2\" Click=\"BTN_Click\">");
                    Console.WriteLine($"<Grid Width=\"{value.Width:0}\">");
                    Console.WriteLine("<Grid.RowDefinitions>");
                    Console.WriteLine("<RowDefinition/>");
                    Console.WriteLine("<RowDefinition Height=\"8\"/>");
                    Console.WriteLine("<RowDefinition/>");
                    Console.WriteLine("</Grid.RowDefinitions>");
                    Console.WriteLine($"<TextBlock Text=\"{value.Content}\" FontSize=\"28\" Foreground=\"{value.Foreground}\" HorizontalAlignment=\"Center\" />");
                    Console.WriteLine($"<TextBlock Grid.Row=\"2\" x:Name=\"{baseName}{name}_Value\" Text=\"\" FontSize=\"28\" Foreground=\"#FF000000\" HorizontalAlignment=\"Left\" />");
                    Console.WriteLine("</Grid>");
                    Console.WriteLine("</Button>");
                }
                else
                {
                    for (int i = 1; ; i++)
                    {
                        if (Names.Add(name))
                            break;

                        if (Names.Add($"{name}_{i}"))
                        {
                            name = $"{name}_{i}";
                            break;
                        }
                    }

                    if (Math.Abs(value.Width - value.Height) < 2)
                        Console.WriteLine($"<Button x:Name=\"Sensor{name}\" Width=\"{value.Width:0}\" Height=\"{value.Height:0}\" Canvas.Left=\"{value.Left}\" Canvas.Top=\"{value.Top:0}\" BorderBrush=\"{value.Strock}\" Background=\"Transparent\" Panel.ZIndex=\"1\" BorderThickness=\"2\" Click=\"BTN_Click\">");
                    else
                        Console.WriteLine($"<Button x:Name=\"RBU_{name}\" Width=\"{value.Width:0}\" Height=\"{value.Height:0}\" Canvas.Left=\"{value.Left}\" Canvas.Top=\"{value.Top:0}\" BorderBrush=\"{value.Strock}\" Background=\"Transparent\" Panel.ZIndex=\"1\" BorderThickness=\"2\" Click=\"BTN_Click\">");
                    Console.WriteLine($"<TextBlock Text=\"{value.Content}\" FontSize=\"28\" Foreground=\"{value.Foreground}\"/>");
                    Console.WriteLine("</Button>");
                }
            }
            Console.WriteLine("</Canvas>");
            Console.WriteLine("<Canvas x:Name=\"RecBorder\" Panel.ZIndex=\"0\">");

            foreach (var item in RecBorder.Values)
            {
                string name = string.IsNullOrEmpty(item.Content) ? $"NoName_{noName++}" : item.Content;
                name = name.Replace(" ", "");
                name = name.Replace("-", "");
                name = name.Replace(".", "");

                for (int i = 1; ; i++)
                {
                    if (Names.Add(name))
                        break;

                    if (Names.Add($"{name}_{i}"))
                    {
                        name = $"{name}_{i}";
                        break;
                    }
                }

                Console.WriteLine($"<Border x:Name=\"RBO_{name}\" Width=\"{item.Width:0}\" Height=\"{item.Height:0}\" Canvas.Left=\"{item.Left:0}\" Canvas.Top=\"{item.Top:0}\" BorderBrush=\"{item.Strock}\" Background=\"Transparent\" Panel.ZIndex=\"0\" BorderThickness=\"2\" >");
                Console.WriteLine($"<TextBlock Text=\"{item.Content}\" FontSize=\"28\" Foreground=\"{item.Foreground}\"/>");
                Console.WriteLine("</Border>");
            }
            Console.WriteLine("</Canvas>");
            Console.WriteLine();
            Console.WriteLine("<Canvas x:Name=\"CirButton\" Panel.ZIndex=\"1\">");

            foreach (var item in CirButton.Values)
            {
                string name = string.IsNullOrEmpty(item.Content) ? $"NoName_{noName++}" : item.Content;
                name = name.Replace(" ", "");
                name = name.Replace("-", "");
                name = name.Replace(".", "");
                for (int i = 1; ; i++)
                {
                    if (Names.Add(name))
                        break;

                    if (Names.Add($"{name}_{i}"))
                    {
                        name = $"{name}_{i}";
                        break;
                    }
                }
                Console.WriteLine($"<Button x:Name=\"ValveAV{name}\" Width=\"{item.Width:0}\" Height=\"{item.Height:0}\" Canvas.Left=\"{item.Left:0}\" Canvas.Top=\"{item.Top:0}\" BorderBrush=\"{item.Strock}\" Background=\"Transparent\" Panel.ZIndex=\"1\" BorderThickness=\"2\" Click=\"BTN_Click\">");
                Console.WriteLine("<Button.Resources>");
                Console.WriteLine("<Style TargetType=\"{x:Type Border}\">");
                Console.WriteLine("<Setter Property=\"CornerRadius\" Value=\"75\"/>");
                Console.WriteLine("</Style>");
                Console.WriteLine("</Button.Resources>");
                Console.WriteLine($"<TextBlock Text=\"{item.Content}\" FontSize=\"32\" Foreground=\"{item.Foreground}\"/>");
                Console.WriteLine("</Button>");
            }
            Console.WriteLine("</Canvas>");
            Console.WriteLine();
            Console.WriteLine("<Canvas x:Name=\"CirBorder\" Panel.ZIndex=\"0\">");
            foreach (var item in CirBorder.Values)
            {
                string name = string.IsNullOrEmpty(item.Content) ? $"NoName_{noName++}" : item.Content;
                name = name.Replace(" ", "");
                name = name.Replace("-", "");
                name = name.Replace(".", "");
                for (int i = 1; ; i++)
                {
                    if (Names.Add(name))
                        break;

                    if (Names.Add($"{name}_{i}"))
                    {
                        name = $"{name}_{i}";
                        break;
                    }
                }
                if (item.Width > 50)
                    Console.WriteLine($"<Border x:Name=\"Sensor{name}\" BorderBrush=\"{item.Strock}\" Width=\"{item.Width:0}\" Height=\"{item.Height:0}\" CornerRadius=\"{item.Height:0}\" BorderThickness=\"2\" Canvas.Left=\"{item.Left:0}\" Canvas.Top=\"{item.Top:0}\" />");
                else
                    Console.WriteLine($"<Border x:Name=\"CBO_{name}\" BorderBrush=\"{item.Strock}\" Width=\"{item.Width:0}\" Height=\"{item.Height:0}\" CornerRadius=\"{item.Height:0}\" BorderThickness=\"2\" Canvas.Left=\"{item.Left:0}\" Canvas.Top=\"{item.Top:0}\" />");
            }
            Console.WriteLine("</Canvas>");
            Console.WriteLine();
            Console.WriteLine("<Canvas x:Name=\"Line\" Panel.ZIndex=\"0\">");
            foreach (var item in Line)
            {
                Console.WriteLine($"<Line X1=\"{item.X1:0}\" Y1=\"{item.Y1:0}\" X2=\"{item.X2:0}\" Y2=\"{item.Y2:0}\" Stroke=\"{item.Foreground}\" StrokeThickness=\"2\"/>");
            }
            Console.WriteLine("</Canvas>");
            Console.WriteLine();
            Console.WriteLine("<Canvas x:Name=\"RawPath\" Panel.ZIndex=\"0\">");
            Console.WriteLine(sbRaw);
            Console.WriteLine("</Canvas>");

        }
    }
}
public class DrawData(double width, double height, double left, double top, string strock = "#000000")
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public double Left { get; } = left;
    public double Top { get; } = top;
    public string Strock { get; set; } = strock;
    public string Content { get; set; } = string.Empty;
    public double Fontsize { get; set; }
    public string Foreground { get; set; } = "#000000";
}

public class DrawLine(string x1, string y1, string x2, string y2, string strock = "#000000")
{
    public string X1 { get; } = x1;
    public string Y1 { get; } = y1;
    public string X2 { get; } = x2;
    public string Y2 { get; } = y2;
    public string Foreground { get; set; } = strock;
}