using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using System.Diagnostics;

namespace Chattr
{
    public partial class FormOAuth : Form
    {
        private FormPreferences m_Prefs;

        public FormOAuth(FormPreferences prefs)
        {
            InitializeComponent();
            m_Prefs = prefs;
        }

        private void FormOAuth_Load(object sender, EventArgs e)
        {
            buttonOK.Enabled = false;
            webBrowser.Navigate(m_Prefs.OAuthURL());
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser web = sender as WebBrowser;
            Debug.WriteLine("DocumentCompleted: " + web.Document.Url);
            if (web.Document.Url.AbsoluteUri == TwitterOAuth.AUTHORIZE_URL)
            {
                Match m = Regex.Match(web.DocumentText, "\\<div id=\"oauth_pin\"\\>\\s+(.*?)\\s+", RegexOptions.Multiline);
                if (m.Success)
                {
                    Debug.WriteLine(m.Groups[0]);
                    if (m.Groups.Count > 1)
                    {
                        Debug.WriteLine("'" + m.Groups[1] + "'");
                        String token = TwitterOAuth.access_token(m.Groups[1].Value);
                        if (token != "")
                        {
                            String[] access_token = token.Split(new String[] { ":" }, StringSplitOptions.None);
                            m_Prefs.SetAccessToken(access_token[0]);
                            m_Prefs.SetAccessTokenSecret(access_token[1]);
                            buttonOK.Enabled = true;
                        }
                    }
                }
            }
        }
    }
}
