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)
            {   //<kbd aria-labelledby="code-desc"><code>5536925</code></kbd>
                Match m = Regex.Match(web.DocumentText, "\\<kbd aria-labelledby=\"code-desc\"\\>\\<code\\>(.*?)\\</code\\>\\</kbd\\>", RegexOptions.Multiline);
                if (m.Success)
                {
                    Debug.WriteLine(m.Groups[0]);
                    if (m.Groups.Count > 1)
                    {
                        Debug.WriteLine("'" + m.Groups[1] + "'");
                        textBox.Text = m.Groups[1].Value;
                    }
                }
            }
        }

        private void textBox_TextChanged(object sender, EventArgs e)
        {
            Debug.WriteLine("TextChanged: '" + textBox.Text + "'");
            Match m = Regex.Match(textBox.Text, "^[0-9]+$", RegexOptions.Multiline);
            if (m.Success)
            {
                buttonOK.Enabled = true;
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("OK_Click");
            Match m = Regex.Match(textBox.Text, "^[0-9]+$", RegexOptions.Multiline);
            if (m.Success)
            {
                Debug.WriteLine("OK_Click: '"+ textBox.Text + "'");
                String token = TwitterOAuth.access_token(textBox.Text);
                if (token != "")
                {
                    String[] access_token = token.Split(new String[] { ":" }, StringSplitOptions.None);
                    m_Prefs.SetAccessToken(access_token[0]);
                    m_Prefs.SetAccessTokenSecret(access_token[1]);
                }
            }
        }

        private void FormOAuth_FormClosing(object sender, FormClosingEventArgs e)
        {
            Debug.WriteLine("FormClosing");
        }
    }
}
