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) =>
            {
                lock (RecentStatusesCollection.Instance)
                    Timeline.Statuses =
                        RecentStatusesCollection.Instance.AsParallel()
                        .Where(tweet => tweet.Type != StatusTypes.DirectMessage)
                        .OrderBy(Settings.Instance.OrderType)
                        .ToList();
            };
        }
        
        public override void RefreshTimeline(int page, int count, bool first)
        {
            NotifyStarted();
            try
            {
                var newTweets = this.GetMainForm().TwitterContext.Status.Where(tweet =>
                        tweet.Type == StatusType.Home &&
                        tweet.Page == page &&
                        tweet.Count == count
                    )
                    .Select(tweet => new StatusInfo(tweet))
                    .AsEnumerable()
                    .Where(tweet =>
                    {
                        lock (RecentStatusesCollection.Instance)
                            return !RecentStatusesCollection.Instance.AsParallel().Contains(tweet);
                    })
                    .ToArray();
                lock (RecentStatusesCollection.Instance)
                    RecentStatusesCollection.Instance.AddRange(newTweets);
                if (!first && newTweets.Any())
                    this.NotifyNewItems(newTweets.OrderByDescending(_ => _));
            }
            finally
            {
                NotifyCompleted();
            }
        }
    }
}
