using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebWindow
{
    public partial class Form1 : Form
    {
        private string client_id = "";
        private string redirect = "https://www.lithium03.info/login/login_success.html";
        public string authentication_code;

        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url_redirect = webBrowser1.Url.ToString();
            Form1.ActiveForm.Text = url_redirect;
            var index = url_redirect.IndexOf(redirect);
            if (index < 0)
                return;
            string auth_str = "?authorization_code=";
            if (url_redirect.IndexOf(auth_str) < 0)
                return;
            authentication_code = url_redirect.Substring(url_redirect.IndexOf(auth_str) + auth_str.Length);
            this.Close();
        }

        private void SetBrowserFeatureControl()
        {
            // http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx


            // FeatureControl settings are per-process
            string path = Application.ExecutablePath;
            string fileName = System.IO.Path.GetFileName(path);

            // make the control is not running inside Visual Studio Designer
            if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0)
                return;

            SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", fileName, 8888);
        }
        // http://stackoverflow.com/questions/18333459/c-sharp-webbrowser-ajax-call
        private void SetBrowserFeatureControlKey(string feature, string appName, uint value)
        {
            using (var regkey =
                Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\" + feature))
            {
                regkey.SetValue(appName, (UInt32)value, Microsoft.Win32.RegistryValueKind.DWord);
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            SetBrowserFeatureControl();

            webBrowser1.Navigate("https://developer.api.bitcasa.com/v1/oauth2/authenticate?client_id="
                + client_id + "&redirect=" + Uri.EscapeUriString(redirect));
        }

    }
}
