using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Twitter;

namespace Kakuretter
{
    public partial class Form2 : Form
    {

        Auth auth;

        public Form2()
        {
            InitializeComponent();

            var settings = Properties.Settings.Default;
            this.auth = new Auth(settings.ConsumerKey, settings.ConsumerSecret);

            // リクエストトークンを取得する
            this.auth.GetRequestToken();

            // ユーザーにRequestTokenを認証してもらう
            this.webBrowser1.Navigate(auth.GetAuthorizeUrl());

        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            Regex rx = new Regex(@"<code>(.*?)</code>",RegexOptions.IgnoreCase);
            MatchCollection mc =
                rx.Matches(
                webBrowser1.DocumentText);
            if (0 < mc.Count)
            {
                foreach (System.Text.RegularExpressions.Match m in mc)
                {
                    this.auth.GetAccessToken(m.Groups[1].Value);
                    var settings = Properties.Settings.Default;
                    settings.AccessToken = this.auth.AccessToken;
                    settings.AccessTokenSecret = this.auth.AccessTokenSecret;
                    settings.UserId = this.auth.UserId;
                    settings.ScreenName = this.auth.ScreenName;
                    settings.Save();

                    Form1.Form1Instance.認証するAToolStripMenuItem.Text = "認証解除(&A)";
                    this.Close();
                }
            }
        }

    }
}
