using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Twitter;
using System.Text.RegularExpressions;

namespace Kakuretter
{

    public partial class Form1 : Form
    {

        public HotKey hotKey;

        void hotKey_HotKeyPush(object sender, EventArgs e)
        {

            if (this.Visible)
            {
                this.Hide();
                this.Close();

                // トレイリストのアイコンを表示する
                notifyIcon1.Icon = new Icon(this.Icon, 40, 40);
                notifyIcon1.Visible = true;
                this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
            }
            else
            {
                // フォームを表示する
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
                this.隠れるHToolStripMenuItem.Text = "隠れる(&H)";
            }


        }

        public Form1()
        {
            InitializeComponent();

            var settings = Properties.Settings.Default;

            if ((bool)settings["HotKeyHidden"] == true)
            {
                this.HotKeyHiddenActivate();
            }

            if (!string.IsNullOrEmpty((string)settings["AccessToken"]))
            {
                認証するAToolStripMenuItem.Text = "認証解除(&A)";
            }

            this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
            this.Location = settings.MyLocation;
            this.Opacity = settings.Opacity;
            Form1.Form1Instance = this;
        }

        public void HotKeyHiddenActivate()
        {
            hotKey = new HotKey(MOD_KEY.ALT, Keys.H);
            hotKey.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
        }

        //Form1オブジェクトを保持するためのフィールド
        private static Form1 _form1Instance;

        //Form1オブジェクトを取得、設定するためのプロパティ
        public static Form1 Form1Instance
        {
            get
            {
                return _form1Instance;
            }
            set
            {
                _form1Instance = value;
            }
        }

        private void textBox3_KeyDown_1(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == System.Windows.Forms.Keys.Enter)
            {

                // 設定ファイルから読み込む
                var settings = Properties.Settings.Default;
                if (settings.UserId == "")
                {
                    Form2 form2 = new Form2();
                    form2.Show();
                    return;
                }
                this.tweet();

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            // 設定ファイルから読み込む
            var settings = Properties.Settings.Default;
            if (settings.UserId == "")
            {
                Form2 form2 = new Form2();
                form2.Show();
                return;
            }
            this.tweet();

        }

        private void tweet()
        {
            if (int.Parse(label2.Text) < 0) return;
            String text = textBox3.Text;
            if (text == "") return;

            Dictionary<string, string> parameters = new Dictionary<string, string>();

            if (textBox1.Text != "")
            {
                if (label1.Text == "url")
                {
                    text += " " + textBox1.Text;
                }
                else
                {
                    text += " #" + textBox1.Text;
                }
            }
            // 設定ファイルから読み込む
            var settings = Properties.Settings.Default;
            Auth auth = new Auth(settings.ConsumerKey, settings.ConsumerSecret,
                            settings.AccessToken, settings.AccessTokenSecret,
                            settings.UserId, settings.ScreenName);
            parameters.Add("status", auth.UrlEncode(text));

            try
            {
                auth.Post("https://api.twitter.com/1.1/statuses/update.json", parameters);
                textBox3.Text = "";
            }
            catch (Exception e)
            {
                notifyIcon1.BalloonTipTitle = "エラー";
                notifyIcon1.BalloonTipText = "ツイートに失敗しました。";
                notifyIcon1.BalloonTipIcon = ToolTipIcon.Error;
                notifyIcon1.ShowBalloonTip(10000);
            }

        }

        private void 認証ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            this.tweetLengthChange();
        }

        private void 隠れるToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.ApplicationExitCall)
            {
                e.Cancel = true;
                this.Hide();
                this.Close();

                // トレイリストのアイコンを表示する
                notifyIcon1.Icon = new Icon(this.Icon, 40, 40);
                notifyIcon1.Visible = true;
                this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {

        }

        private void 終了ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;

            var settings = Properties.Settings.Default;

            if (settings.HotKeyHidden == true)
            {
                hotKey.Dispose();
            }
            Application.Exit();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                if (this.Visible)
                {
                    this.Hide();
                    this.Close();

                    // トレイリストのアイコンを表示する
                    notifyIcon1.Icon = new Icon(this.Icon, 40, 40);
                    notifyIcon1.Visible = true;
                    this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
                }
                else
                {
                    // フォームを表示する
                    this.Visible = true;
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                    this.隠れるHToolStripMenuItem.Text = "隠れる(&H)";
                }
            }
        }

        private void 設定ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {
            if (label1.Text == "#")
            {
                label1.Text = "url";
                label1.TextAlign = ContentAlignment.MiddleCenter;
            }
            else
            {
                label1.Text = "#";
            }
            tweetLengthChange();
        }

        private void 設定OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form3 form3 = new Form3();
            form3.Show();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            this.tweetLengthChange();
        }

        private void tweetLengthChange()
        {
            int tl = 140;
            Regex regex = new Regex(@"(?:^|[\s　]+)((?:https?|ftp):\/\/[^\s　]+)");
            Match m;
            if (0 < textBox1.TextLength)
            {
                if (label1.Text == "url")
                {
                    tl -= textBox1.TextLength + 1;
                }
                else
                {
                    tl -= textBox1.TextLength + 2;
                }
                m = regex.Match(textBox1.Text);
                if (m.Success)
                {
                    while (m.Success)
                    {
                        if (22 < m.Length)
                        {
                            tl += m.Length;
                            tl -= 22;
                        }
                        m = m.NextMatch();
                    }
                }
            }

            m = regex.Match(textBox3.Text);

            tl -= textBox3.TextLength;

            if (m.Success)
            {
                while (m.Success)
                {
                    if (22 < m.Length)
                    {
                        tl += m.Length;
                        tl -= 22;
                    }
                    m = m.NextMatch();
                }
            }

            if (tl < 0)
            {
                this.label2.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                this.label2.ForeColor = SystemColors.ControlText;
            }

            this.label2.Text = tl.ToString();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.H && e.Alt == true)
            {
                e.SuppressKeyPress = true;
                if (this.Visible)
                {
                    this.Hide();
                    this.Close();

                    // トレイリストのアイコンを表示する
                    notifyIcon1.Icon = new Icon(this.Icon, 40, 40);
                    notifyIcon1.Visible = true;
                    this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
                }
                else
                {
                    // フォームを表示する
                    this.Visible = true;
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                    this.隠れるHToolStripMenuItem.Text = "隠れる(&H)";
                }
            }

            if (e.KeyCode == Keys.A && e.Alt == true)
            {
                e.SuppressKeyPress = true;
                this.auth();
            }

            if (e.KeyCode == Keys.O && e.Alt == true)
            {
                e.SuppressKeyPress = true;
                Form3 form3 = new Form3();
                form3.Show();
            }
        }

        private void 認証するAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.auth();
        }

        private void auth()
        {
            var settings = Properties.Settings.Default;
            if (!string.IsNullOrEmpty((string)settings["AccessToken"]))
            {
                //認証解除ボタンが押されたときに本当に解除するかの確認を行う。
                DialogResult result = MessageBox.Show("本当に認証を解除しますか？",
                    "確認",
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button2);

                if (result == DialogResult.Yes)
                {
                    settings.AccessToken = "";
                    settings.AccessTokenSecret = "";
                    settings.UserId = "";
                    settings.ScreenName = "";
                    settings.Save();
                    認証するAToolStripMenuItem.Text = "認証する(&A)...";
                }
            }
            else
            {
                Form2 form2 = new Form2();
                form2.Show();
            }
        }

        private void 隠れるHToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
                this.Close();

                // トレイリストのアイコンを表示する
                notifyIcon1.Icon = new Icon(this.Icon, 40, 40);
                notifyIcon1.Visible = true;
                this.隠れるHToolStripMenuItem.Text = "表示する(&H)";
            }
            else
            {
                // フォームを表示する
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
                this.隠れるHToolStripMenuItem.Text = "隠れる(&H)";
            }
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void Form1_LocationChanged(object sender, EventArgs e)
        {
            var settings = Properties.Settings.Default;
            settings.MyLocation = this.Location;
            settings.Save();
        }

        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            //EnterやEscapeキーでビープ音が鳴らないようにする
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
            {
                e.Handled = true;
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //EnterやEscapeキーでビープ音が鳴らないようにする
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
            {
                e.Handled = true;
            }
        }

    }
}
