using System.Linq;
using System.Text.RegularExpressions;
using LinqToTwitter;

namespace Azyobuzi.Twirunrun
{
    public class MentionsTabPage : TimelineTabPage
    {
        public MentionsTabPage(TwirunrunTabControl owner, TabInfo tabsettings)
            : base(owner, tabsettings)
        {
            var mentionCheckRegex = new Regex(
                string.Format(@"[@＠]{0}(\W|$)", Settings.Instance.MyScreenName.RegexEscape()),
                RegexOptions.IgnoreCase);

            RecentStatusesCollection.Instance.CollectionChanged += (sender, e) =>
            {
                //リストに反映
                Timeline.Statuses =
                    RecentStatusesCollection.Instance.AsParallel()
                    .Where(tweet =>
                        tweet.Type != StatusTypes.DirectMessage &&
                        mentionCheckRegex.IsMatch(tweet.Text))
                    .OrderBy(Settings.Instance.OrderType)
                    .ToList().AsReadOnly();
                //新着通知
                if (e.NewItems.Count != 0)
                {
                    var newTweets = e.NewItems.OfType<StatusInfo>().Where(tweet => mentionCheckRegex.IsMatch(tweet.Text));
                    if (newTweets.Any()) NotifyNewItems(newTweets.OrderByDescending(_ => _));
                }
            };
        }

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