class WatchThread(forms.Form):
    reddit_thread_url = forms.URLField(label='', max_length=500, widget=forms.TextInput(attrs={'placeholder':
                                       'e.g. https://www.reddit.com/r/learnpython/comments/5jgbiq/python_oop_series/'}))
    watch_interval = forms.ChoiceField(choices=date_options,
                                       label='Select the frequency of which you would like to be updated',
                                       widget=forms.RadioSelect()) class WatchSubreddit(forms.Form):
    subreddit_name = forms.CharField(label='', max_length=30, widget=forms.TextInput(attrs={'placeholder':
                                     'e.g. learnpython'}))
    watch_interval = forms.ChoiceField(choices=date_options,
                                       label='Select the frequency of which you would like to be updated',
                                       widget=forms.RadioSelect()) class WatchUser(forms.Form):
    username = forms.CharField(label='', max_length=30, widget = forms.TextInput(attrs={'placeholder': 'e.g. wil'}))
    watch_interval = forms.ChoiceField(choices=date_options,
                                       label='Select the frequency of which you would like to be updated',
                                       widget=forms.RadioSelect()) def get_reddit_thread(reddit_url):
    thread = r.submission(url=reddit_url)
    return thread def get_reddit_comments_from_thread(thread):
    thread.comments.replace_more(limit=0)
    thread_comments = thread.comments.list()
    return thread_comments def user_exists(user):
    try:
        r.redditor(user).fullname
    except prawcore.exceptions.NotFound:
        return False
    return True def subreddit_exists(subreddit):
    try:
        r.subreddit(subreddit).fullname
    except prawcore.exceptions.Redirect:
        return False
    return True def get_subreddit_threads(subreddit_name, fetch_amount):
    thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
    return thread def get_user_comments(username, fetch_amount):
    comments = r.redditor(username).comments.new(limit=fetch_amount)
    return comments def get_user_threads(username, fetch_amount):
    threads = r.redditor(username).submissions.new(limit=fetch_amount)
    return threads def authorize_reddit_account(state):
    a = praw.Reddit('bot2', user_agent='django web authentication app v0.5 (by /u/ericleepa)')
    url = a.auth.url(['identity'], state, duration='temporary')
    return url def reddit_code_to_username(code):
    a = praw.Reddit('bot2', user_agent='django web authentication app v0.5 (by /u/ericleepa)')
    a.auth.authorize(code)
    return a.user.me().name class WatchedThread(models.Model):
    user = models.ForeignKey(User)
    url = models.CharField(max_length=500)
    title = models.CharField(max_length=500)
    thread_date = models.CharField(max_length=50)
    archived = models.BooleanField(default=False)
    self_post = models.BooleanField(default=False)
    self_text = models.CharField(max_length=10000, null=True, blank=True)
    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.title class WatchedComment(models.Model):
    parent_thread = models.ForeignKey(WatchedThread, on_delete=models.CASCADE)
    comment_author = models.CharField(max_length=100, null=True, blank=True)
    url = models.CharField(max_length=500)
    text = models.CharField(max_length=10000)

    def __str__(self):
        return self.url 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 class WatchedUser(models.Model):
    user = models.ForeignKey(User)
    watched_username = 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.watched_username class WatchedUserComment(models.Model):
    parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
    url = models.CharField(max_length=500)
    text = models.CharField(max_length=10000)

    def __str__(self):
        return self.url class WatchedUserThread(models.Model):
    parent_user = models.ForeignKey(WatchedUser, 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
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import user_passes_test, login_required
from django.contrib.auth.models import User
from django.core.management import call_command
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.utils import timezone
from redditpoller.forms import WatchThread, WatchSubreddit, WatchUser
from redditpoller.poller import get_reddit_thread, get_reddit_comments_from_thread, user_exists, subreddit_exists, \
    get_subreddit_threads, get_user_comments, get_user_threads, authorize_reddit_account, reddit_code_to_username
from redditpoller.models import WatchedThread, WatchedComment, WatchedSubreddit, WatchedSubredditThread, WatchedUser, \
    WatchedUserComment, WatchedUserThread
    from uuid import uuid4


def home_page(request):
    return render(request, 'homepage.html')


def about(request):
    return render(request, 'about.html')


def redirect_to_reddit_auth(request):
    reddit_state = str(uuid4())
    request.session['reddit_state'] = reddit_state
    auth_url = authorize_reddit_account(reddit_state)
    print(request.session['reddit_state'])
    return redirect(auth_url)


def callback(request):
    if request.method == 'GET':
        if request.session['reddit_state'] == request.GET.get('state'):
            code = request.GET.get('code')
            reddit_username = reddit_code_to_username(code)
            if User.objects.filter(username=reddit_username).exists():
                user = authenticate(username=reddit_username)
                login(request, user)
                return redirect('/')
            else:
                User.objects.create_user(username=reddit_username)
                user = authenticate(username=reddit_username)
                login(request, user)
            return redirect('/')
        else:
            return HttpResponseBadRequest('invalid request')
    else:
        return HttpResponseBadRequest('invalid request')


def logout_view(request):
    logout(request)
    return HttpResponseRedirect("/homepage/")


@login_required(login_url='/homepage/', redirect_field_name=None)
def index(request):
    return render(request, 'index.html')


@login_required(login_url='/homepage/', redirect_field_name=None)
def watch_thread(request):
    form = WatchThread(initial={'watch_interval': '1'})
    return render(request, 'watchthread.html', {'form': form})


@login_required(login_url='/homepage/', redirect_field_name=None)
def watch_subreddit(request):
    form = WatchSubreddit(initial={'watch_interval': '1'})
    return render(request, 'watchsubreddit.html', {'form': form})


@login_required(login_url='/homepage/', redirect_field_name=None)
def watch_user(request):
    form = WatchUser(initial={'watch_interval': '1'})
    return render(request, 'watchuser.html', {'form': form})


@login_required(login_url='/homepage/', redirect_field_name=None)
def watched_thread(request):
    if request.method == 'POST':
        form = WatchThread(request.POST)
        if form.is_valid():
            reddit_url = form.cleaned_data['reddit_thread_url']
            watch_interval = form.cleaned_data['watch_interval']
            try:
                if WatchedThread.objects.filter(user=request.user).count() > 9:
                    return render(request, 'error.html', {'error': 'Each account can only have up to ten watched '
                                                                   'threads'})
                praw_thread = get_reddit_thread(reddit_url)

                if WatchedThread.objects.filter(user=request.user, url=praw_thread.permalink).exists():