using HtmlAgilityPack;
using ICSharpCode.TextEditor.Document;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace 开发辅助工具.Tools
{
    public partial class FrmXpath : DockContent
    {
        public FrmXpath()
        {
            InitializeComponent();
            CbbXMLType.SelectedIndex = 0;
            textEditorControl1.IsReadOnly = true;
        }

        private void RySearchXpath_OnSearch(object sender, EventArgs e)
        {
            string text = "";
            string format = "XML";
            try
            {
                if (CbbXMLType.SelectedIndex == 0)
                {
                    format = "XML";
                    System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
                    xml.LoadXml(TxtXML.Text);
                    var node = xml.SelectNodes(RySearchXpath.Text);
                    if (node != null)
                    {
                        for (int i = 0; i < node.Count; i++)
                        {
                            if (text != "") { text += "\r\n\r\n"; }
                            text += node[i].OuterXml;
                        }
                    }
                }
                else if (CbbXMLType.SelectedIndex == 1)
                {
                    format = "HTML";
                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                    htmlDoc.LoadHtml(TxtXML.Text);
                    HtmlNodeCollection anchors = htmlDoc.DocumentNode.SelectNodes(RySearchXpath.Text);
                    if (anchors != null)
                    {
                        for (int i = 0; i < anchors.Count; i++)
                        {
                            if (text != "") { text += "\r\n\r\n"; }
                            text += anchors[i].OuterHtml;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(format);
            textEditorControl1.Text = text;
        }

        private void FrmXpath_Load(object sender, EventArgs e)
        {

        }

        private void TxtXML_DoubleClick(object sender, EventArgs e)
        {
            ryControls.Controls.RichTextBox2 txt = (ryControls.Controls.RichTextBox2)sender;
            开发辅助工具.Controls.FrmText frm = new Controls.FrmText
            {
                Icon = Icon
            };
            frm.richTextBox1.Text = txt.Text;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txt.Text = frm.richTextBox1.Text;
            }
        }
    }
}
