# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
#     user = models.ForeignKey(User)
#     name = models.CharField(max_length=30)
#     submitted_date = models.DateTimeField(default=timezone.now)
#     last_checked_date = models.DateTimeField(default=timezone.now)
#     watch_interval = models.IntegerField(blank=True, null=True)
# 
#     def __str__(self):
#         return self.name
# 
# class WatchedSubredditThread(models.Model):
#     parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
#     url = models.CharField(max_length=500)
#     title = models.CharField(max_length=500)
#     thread_date = models.CharField(max_length=50)
# 
#     def __str__(self):
#         return self.title
# 
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
#     thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
#     return thread
# 
# def notify_user(redditor, message):
#     r.redditor(redditor).message('Reddit Watcher', message)


from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta
                # keep db from growing, only need the newest 100 submissions as a comparison
                if linked_threads.count() > 200:
                    # This works, but probably can be broken up into its own "cleanup function"
                    number_to_delete = abs(100 - linked_threads.count())
                    purge = linked_threads.order_by('thread_date')[:number_to_delete].values_list("id", flat=True)
                    WatchedSubredditThread.objects.filter(pk__in=list(purge)).delete()
                thread_list = []
                new_thread_count = 0
                for sthread in new_threads:
                    if linked_threads.filter(url=sthread.permalink).exists():
                        pass
                    else:
                        thread_list.append([sthread.title, sthread.permalink])
                        t = WatchedSubredditThread(parent_subreddit=subreddit, url=sthread.permalink,
                                                   title=sthread.title, thread_date=sthread.created)
                        t.save()
                        new_thread_count += 1

                if new_thread_count == 0:
                    pass
                else:
                    formatted_thread_titles = ''
                    limit_threads = 5
                    for thr in thread_list:
                        if limit_threads > 0:
                            formatted_thread_titles += '\n\n' + thr[0] + ' - [Link](https://reddit.com{})'.format(thr[1])
                            limit_threads -= 1
                        else:
                            break
                    username = subreddit.user.username

# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
#     user = models.ForeignKey(User)
#     name = models.CharField(max_length=30)
#     submitted_date = models.DateTimeField(default=timezone.now)
#     last_checked_date = models.DateTimeField(default=timezone.now)
#     watch_interval = models.IntegerField(blank=True, null=True)
# 
#     def __str__(self):
#         return self.name
# 
# class WatchedSubredditThread(models.Model):
#     parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
#     url = models.CharField(max_length=500)
#     title = models.CharField(max_length=500)
#     thread_date = models.CharField(max_length=50)
# 
#     def __str__(self):
#         return self.title
# 
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
#     thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
#     return thread
# 
# def notify_user(redditor, message):
#     r.redditor(redditor).message('Reddit Watcher', message)


# Path: redditpoller/management/commands/check_watched_subreddits.py
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta

                # keep db from growing, only need the newest 100 submissions as a comparison
                if linked_threads.count() > 200:
                    # This works, but probably can be broken up into its own "cleanup function"
                    number_to_delete = abs(100 - linked_threads.count())
                    purge = linked_threads.order_by('thread_date')[:number_to_delete].values_list("id", flat=True)
                    WatchedSubredditThread.objects.filter(pk__in=list(purge)).delete()
                thread_list = []
                new_thread_count = 0
                for sthread in new_threads:
                    if linked_threads.filter(url=sthread.permalink).exists():
                        pass
                    else:
                        thread_list.append([sthread.title, sthread.permalink])
                        t = WatchedSubredditThread(parent_subreddit=subreddit, url=sthread.permalink,
                                                   title=sthread.title, thread_date=sthread.created)
                        t.save()
                        new_thread_count += 1

                if new_thread_count == 0:
                    pass
                else:
                    formatted_thread_titles = ''
                    limit_threads = 5
                    for thr in thread_list:
                        if limit_threads > 0:
                            formatted_thread_titles += '\n\n' + thr[0] + ' - [Link](https://reddit.com{})'.format(thr[1])
                            limit_threads -= 1
                        else:
                            break
                    username = subreddit.user.username

                    notify_user(username, '{} new thread(s) in the subreddit **"{}"** - view subreddit [here.]'