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) =>
            {
                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 newDMs = new[] { DirectMessageType.SentTo, DirectMessageType.SentBy }.SelectMany(type =>
                        this.GetMainForm().TwitterContext.DirectMessage.Where(dm =>
                            dm.Type == type &&
                            dm.Page == page &&
                            dm.Count == count
                        )
                    ).Select(dm => new StatusInfo(dm))
                    .AsEnumerable()
                    .Where(dm =>
                    {
                        lock (RecentStatusesCollection.Instance)
                            return !RecentStatusesCollection.Instance.AsParallel().Contains(dm);
                    })
                    .ToArray();
                lock (RecentStatusesCollection.Instance)
                    RecentStatusesCollection.Instance.AddRange(newDMs);
                if (!first && newDMs.Any())
                    this.NotifyNewItems(newDMs.OrderByDescending(_ => _));
            }
            finally
            {
                NotifyCompleted();
            }
        }
    }
}
