using MarketData;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace TradeBlotter.UIUtils
{
  public class WebBrowserHelper
  {
    private WebBrowserHelper()
    {
    }
    public static bool SetWebBrowserCompatibility()
    {
      RegistryKey regkey = null;

      try
      {
        int browserVersion;
        int regVal;
        browserVersion = BrowserVersion();

        // set the appropriate IE verbrowsersion
        if (browserVersion >= 11)regVal = 11001;
        else if (browserVersion == 10)regVal = 10001;
        else if (browserVersion == 9)regVal = 9999;
        else if (browserVersion == 8)regVal = 8888;
        else regVal = 7000;

        regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
        if (null == regkey)
        {
          regkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree);
          if (null == regkey) return false;
        }
        if (regkey.GetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe") == null)regkey.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe", regVal, RegistryValueKind.DWord);
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[SetWebBrowserCompatibility]{0}",exception.ToString()));
        return false;
      }
      finally
      {
        if (regkey != null) {regkey.Close(); regkey.Dispose();}
      }
    }
    private static int BrowserVersion()
    {
      string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
      string[] versionTargets = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };
      int maxVer = 0;
      for (int index = 0; index < versionTargets.Length; index++)
      {
        object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, versionTargets[index], "0");
        string strVal = System.Convert.ToString(objVal);
        if (null == strVal) continue;
        int iPos = strVal.IndexOf('.');
        if (iPos > 0)strVal = strVal.Substring(0, iPos);
        int res = 0;
        if (int.TryParse(strVal, out res))maxVer = Math.Max(maxVer, res);
      } 
      return maxVer;
    }
  }
}

