using System.Linq;
using LinqToTwitter;

namespace Azyobuzi.Twirunrun
{
    public class HomeTimelineTabPage : TimelineTabPage
    {
        public HomeTimelineTabPage(TwirunrunTabControl owner, TabInfo tabsettings)
            : base(owner, tabsettings)
        {
            RecentStatusesCollection.Instance.CollectionChanged += (sender, e) =>
            {
                Timeline.Statuses =
                    RecentStatusesCollection.Instance.AsParallel()
                    .Where(tweet => tweet.Type != StatusTypes.DirectMessage)
                    .OrderBy(Settings.Instance.OrderType)
                    .ToList().AsReadOnly();
                //新着通知
                if (e.NewItems.Count != 0)
                {
                    var newTweets = e.NewItems.OfType<StatusInfo>().Where(tweet => tweet.Type != StatusTypes.DirectMessage);
                    if (newTweets.Any()) this.NotifyNewItems(newTweets.OrderByDescending(_ => _));
                }
            };
        }

        public override void RefreshTimeline(int page, int count)
        {
            NotifyStarted();
            RecentStatusesCollection.Instance.AddRange(
                Owner.Owner.TwitterContext.Status.Where(tweet =>
                    tweet.Type == StatusType.Home &&
                    tweet.Page == page &&
                    tweet.Count == count
                ).Select(tweet => new StatusInfo(tweet))
                .Where(tweet => !RecentStatusesCollection.Instance.AsParallel().Contains(tweet))
            );
            NotifyCompleted();
        }
    }
}
