using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Valg.EVA.Skanning.UserInterfaceElements.Help;

namespace Valg.EVA.Skanning.UserInterfaceElements.Login
{
    public partial class LoginWindow : IHelpContributor
    {
        public LoginWindow(ILoginWindowViewModel viewModel)
        {
            InitializeComponent();
            DataContext = ViewModel = viewModel;

            
            var host = new System.Windows.Forms.Integration.WindowsFormsHost();

            
            var windowsFormsWebBrowser = new WebBrowser();
            windowsFormsWebBrowser.DocumentCompleted += WindowsFormsWebBrowserOnDocumentCompleted;

            
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);

            windowsFormsWebBrowser.Navigate(viewModel.LogonStartUrl);

            
            
            var webBrowserActiveXInstance = (SHDocVw.WebBrowser)windowsFormsWebBrowser.ActiveXInstance;
            webBrowserActiveXInstance.NavigateError += WebBrowserActiveXInstanceOnNavigateError;

            host.Child = windowsFormsWebBrowser;
            browserHost.Children.Add(host);
        }

        public ILoginWindowViewModel ViewModel { get; set; }

        private void WindowsFormsWebBrowserOnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs webBrowserDocumentCompletedEventArgs)
        {
            IHtmlDocument document = new HtmlDocument(sender as WebBrowser);
            ViewModel.PageLoaded(webBrowserDocumentCompletedEventArgs.Url, document);
            
            document = null;

            if (ViewModel.CloseLoginWindow)
            {
                Close();
            }
        }

        private void WebBrowserActiveXInstanceOnNavigateError(object pdisp, ref object url, ref object frame, ref object statuscode, ref bool cancel)
        {
            ViewModel.ShowErrorInformation();
        }

        public LoginWindowLoginResult Result => ViewModel.Result;

        public string HelpContributionId => HelpContributionIds.Loginvindu;

        public void HideScriptErrors(WebBrowser wb, bool Hide)
        {
            FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser != null)
            {
                object objComWebBrowser = fiComWebBrowser.GetValue(wb);
                objComWebBrowser?.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });
            }
        }

        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
        private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
    }
}
