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

namespace Azyobuzi.Twirunrun
{
    public class MentionsTabPage : TimelineTabPage
    {
        public MentionsTabPage(TabInfo tabsettings)
            : base(tabsettings)
        {
            RecentStatusesCollection.Instance.CollectionChanged += (sender, e) =>
            {
                //リストに反映
                lock (RecentStatusesCollection.Instance)
                    Timeline.Statuses =
                        RecentStatusesCollection.Instance.AsParallel()
                        .Where(IsReplyToMe)
                        .OrderBy(Settings.Instance.OrderType)
                        .ToList();
                //新着通知
                if (e.NewItems.Count != 0 && !first)
                {
                    var newTweets = e.NewItems.OfType<StatusInfo>().Where(IsReplyToMe);
                    if (newTweets.Any()) NotifyNewItems(newTweets.OrderByDescending(_ => _));
                }
            };
        }

        private bool IsReplyToMe(StatusInfo tweet)
        {
            return tweet.Type != StatusTypes.DirectMessage &&
                tweet.Text.RegexIsMatch(
                    string.Format(
                        @"[@＠]{0}(\W|$)",
                        this.GetMainForm().TwitterContext.AuthorizedClient.ScreenName.RegexEscape()
                    ),
                    RegexOptions.IgnoreCase);
        }

        private bool first;

        public override void RefreshTimeline(int page, int count, bool first)
        {
            NotifyStarted();
            try
            {
                this.first = first;
                var newTweets = this.GetMainForm().TwitterContext.Status.Where(tweet =>
                        tweet.Type == StatusType.Mentions &&
                        tweet.Page == page &&
                        tweet.Count == count
                    )
                    .Select(tweet => new StatusInfo(tweet))
                    .AsEnumerable()
                    .Where(tweet =>
                    {
                        lock (RecentStatusesCollection.Instance)
                            return !RecentStatusesCollection.Instance.AsParallel().Contains(tweet);
                    })
                    .ToArray();
                if (newTweets.Any())
                {
                    lock (RecentStatusesCollection.Instance)
                        RecentStatusesCollection.Instance.AddRange(newTweets);
                }
                first = false;
            }
            finally
            {
                NotifyCompleted();
            }
        }
    }
}
