using System.Linq;
using LinqToTwitter;

namespace Azyobuzi.Twirunrun
{
    public class DirectMessagesTimelineTabPage : TimelineTabPage
    {
        public DirectMessagesTimelineTabPage(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(
                new[] { DirectMessageType.SentTo, DirectMessageType.SentBy }.SelectMany(type =>
                    Owner.Owner.TwitterContext.DirectMessage.Where(dm =>
                        dm.Type == type &&
                        dm.Page == page &&
                        dm.Count == count
                    )
                ).Select(dm => new StatusInfo(dm))
                .Where(dm => !RecentStatusesCollection.Instance.AsParallel().Contains(dm))
            );
            NotifyCompleted();
        }
    }
}
