using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Azyobuzi.Twirunrun
{
    public partial class UpdateStatusPanel : UserControl
    {
        public UpdateStatusPanel()
        {
            InitializeComponent();
        }

        const int MAXIMUM_LENGTH = 140;

        public event EventHandler RunUpdateStatus;

        protected virtual void OnRunUpdateStatus(EventArgs e)
        {
            if (RunUpdateStatus != null) RunUpdateStatus(this, e);
        }
        
        /// <summary>
        /// statusBox.Text
        /// </summary>
        [Browsable(true)]
        public override string Text
        {
            get
            {
                return statusBox.Text;
            }
            set
            {
                if (statusBox.Text != value)
                {
                    statusBox.Text = value;
                    OnTextChanged(EventArgs.Empty);
                }
            }
        }

        public void SetReplyTo(string replyToId, string[] replyToScreenName, bool isReplyAll)
        {
            if (replyToScreenName.Length == 0) return;
            this.ReplyToId = replyToId;
            if (replyToScreenName.Length == 1)
                this.Text = string.Format("@{0} {1}", replyToScreenName[0], this.Text);
            else
            {
                string atText = "@" + string.Join(" @", replyToScreenName) + " ";
                if (!isReplyAll) atText = "." + atText;
                this.Text = atText + this.Text;
            }
            this.Focus();
            if (statusBox.TextLength != 0) statusBox.Select(statusBox.TextLength, 0);
        }

        private string replytoid;
        public string ReplyToId
        {
            set
            {
                if (replytoid != value)
                {
                    replytoid = value;
                    OnReplyToIdChanged(EventArgs.Empty);
                }
            }
            get
            {
                return replytoid;
            }
        }

        public event EventHandler ReplyToIdChanged;

        protected virtual void OnReplyToIdChanged(EventArgs e)
        {
            if (ReplyToIdChanged != null) ReplyToIdChanged(this, e);
        }

        private void statusBox_TextChanged(object sender, EventArgs e)
        {
            var length = statusBox.TextLength;
            restLbl.Text = string.Format("残り{0}文字", MAXIMUM_LENGTH - length);
            if (length > MAXIMUM_LENGTH)
                restLbl.ForeColor = Color.Red;
            else
                restLbl.ForeColor = SystemColors.ControlText;
            if (length == 0) ReplyToId = null;
        }

        private void updateBtn_Click(object sender, EventArgs e)
        {
            OnRunUpdateStatus(EventArgs.Empty);
        }

        public void Clear()
        {
            statusBox.Clear();
            ReplyToId = "";
        }
    }
}
