using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace Azyobuzi.Twirunrun
{
    public abstract class TimelineTabPage : TabPage
    {
        public TimelineTabPage(TwirunrunTabControl owner, TabInfo tabsettings)
        {
            Owner = owner;
            TabSettings = tabsettings;
            this.Text = TabSettings.Name;
            Timeline.Dock = DockStyle.Fill;
            this.Controls.Add(Timeline);
            TabSettings.PropertyChanged += TabSettings_PropertyChanged;
            Timeline.SelectedIndexChanged += (sender, e) =>
                Owner.Owner.ShowDetailStatus(Timeline.Statuses[Timeline.SelectedIndex]);
            Timeline.DoubleClick += (sender, e) =>
            {
                if (Timeline.SelectedIndex == -1) return;
                var selecting = Timeline.Statuses[Timeline.SelectedIndex];
                Owner.Owner.UpdateStatusPanel.SetReplyTo(
                     selecting.Type == StatusTypes.Retweet ?
                            selecting.Tweet.Retweet.ID : selecting.Id,
                    new[] { selecting.User.Identifier.ScreenName },
                    false
                );
            };
        }

        public TwirunrunTabControl Owner { private set; get; }

        public StatusesListBox Timeline = new StatusesListBox();

        public TabInfo TabSettings { private set; get; }

        private void TabSettings_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            e.PropertyName.SelectCase()
                .Case("Name", () => { if (!refreshing) this.Text = TabSettings.Name; });
        }

        public abstract void RefreshTimeline(int page, int count);
        public virtual void RefreshTimeline()
        {
            RefreshTimeline(1, TabSettings.GetHits);
        }

        private bool refreshing = false;

        /// <summary>
        /// 取得開始を通知します。
        /// </summary>
        protected void NotifyStarted()
        {
            refreshing = true;
            this.Invoke((MethodInvoker)(() => this.Text = "更新中..."));
            Owner.Owner.StatusChange(TabSettings.Name + "を更新中");
        }

        /// <summary>
        /// 取得完了を通知します。
        /// </summary>
        protected void NotifyCompleted()
        {
            Owner.Owner.StatusChange(TabSettings.Name + "：取得しました");
            refreshing = false;
            this.Invoke((MethodInvoker)(() => this.Text = TabSettings.Name));
        }

        /// <summary>
        /// 新着通知をします。設定によっては何もしない
        /// </summary>
        protected void NotifyNewItems(IEnumerable<StatusInfo> newItems)
        {
            //TODO
        }
    }
}
