using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using CsQuery;
using CsQuery.ExtensionMethods;

namespace VCommon.Logging.Viewer.Utility
{
   public class WebBrowserUtility
    {

        public static void LoadWebBrowserResource(WebBrowser webBrowser)
        {

            webBrowser.DocumentText = LoadWebBrowserResource();
        }

        public static string LoadWebBrowserResource()
        {
            var resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            CQ doc = ReadResourceFile(resourceNames.FirstOrDefault(c => Path.GetExtension(c) == ".html"));
            resourceNames.ForEach(c =>
            {
                var fileExtension = Path.GetExtension(c);
                if (fileExtension == ".css" || fileExtension == ".js")
                {
                    doc[$"#{Path.GetExtension(Path.GetFileNameWithoutExtension(c))?.TrimStart('.')}"].Text($"{ReadResourceFile($"{c}")}");
                }
            });
            return doc.Render(OutputFormatters.Create(DomRenderingOptions.None, HtmlEncoders.None));
        }
        private static string ReadResourceFile(string resourceName)
        {
            if (string.IsNullOrEmpty(resourceName)) throw new ArgumentNullException(nameof(resourceName));
            return new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException()).ReadToEnd();
        }

        public static void SendMouseWheel(Message m,WebBrowser webBrowser)
        {
            var handle = webBrowser.Handle;
            handle = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "Shell Embedding", null);
            handle = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "Shell DocObject View", null);
            handle = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "Internet Explorer_Server", null);
            NativeMethods.SendMessage(handle, 0x020A, m.WParam, m.LParam);
        }
    }
}
