# Path: profiles/forms.py
# class ReportForm(forms.Form):
#     summary = forms.CharField(required=True,
#                               widget=forms.TextInput(attrs={'required': 'required',
#                                                             'class': 'form-control'}))
#     details = forms.CharField(widget=forms.Textarea, required=False)
# 
# Path: profiles/models.py
# class UserProfile(models.Model):
#     """A user profile."""
#     user = models.ForeignKey(User)
#     feeds = models.ManyToManyField(to=Feed, through='profiles.Subscription')
#     entries = models.ManyToManyField(to=Entry,
#                                      through='profiles.UserEntryDetail')
#     next_slug = RandomSlugField(slug_length=10)
# 
#     def __unicode__(self):
#         return u"{}'s profile".format(self.user.username)
# 
#     def subscribe(self, feed):
#         Subscription.objects.create(profile=self, feed=feed)
# 
#     def unsubscribe(self, feed):
#         Subscription.objects.get(profile=self, feed=feed).delete()
#         self._get_entries(feed).delete()
# 
#     def mark_read(self, feed):
#         entries = self._get_entries(feed)
#         for entry in entries:
#             entry.read = True
#             entry.save()
# 
#     def mark_unread(self, feed):
#         entries = self._get_entries(feed)
#         for entry in entries:
#             entry.read = False
#             entry.save()
# 
#     def unread_entries(self, feed):
#         return self._get_entries(feed).filter(read=False).count()
# 
#     def _get_entries(self, feed):
#         return UserEntryDetail.objects.filter(profile=self, entry__feed=feed)
# 
# class UserEntryDetail(models.Model):
#     profile = models.ForeignKey(to=UserProfile)
#     entry = models.ForeignKey(to=Entry)
#     read = models.BooleanField()
# 
#     def __unicode__(self):
#         return u'User: {}, Entry: {}, Read: {}'.format(
#                                                 self.profile.user.username,
#                                                 self.entry,
#                                                 self.read)
# 
# class Subscription(models.Model):
#     profile = models.ForeignKey(to=UserProfile)
#     feed = models.ForeignKey(to=Feed)
# 
#     def unread_entries_num(self):
#         unread_entries = UserEntryDetail.objects.filter(read=False,
#                                                         profile=self.profile,
#                                                         entry__feed=self.feed)
#         return unread_entries.count()
# 
# Path: feeds/forms.py
# class FeedForm(ModelForm):
#     class Meta:
#         model = Feed
#         fields = ['link']
#         widgets = {
#             'link': TextInput(attrs={'placeholder': 'Paste RSS address here!',
#                                      'id': 'feed-url-input'})
#         }
# 
#     def clean(self):
#         cleaned_data = super(FeedForm, self).clean()
#         parser = feedparser.parse(cleaned_data.get('link'))
#         if parser.feed == {} or parser.status != 200:
#             raise ValidationError("The link provided is not a valid feed.")
#         return cleaned_data
# 
# Path: feeds/models.py
# class Feed(models.Model):
#     title = models.CharField(max_length=200)
#     link = models.CharField(max_length=1000)
# 
#     def __unicode__(self):
#         return self.title
# 
# class Entry(models.Model):
#     title = models.CharField(max_length=200)
#     link = models.CharField(max_length=1000)
#     feed = models.ForeignKey(to=Feed)
#     published = models.DateTimeField()
# 
#     def __unicode__(self):
#         return u'{}: {}'.format(self.feed, self.title)
# 
# Path: feeds/tasks.py
# def poll_feed(feed):
#     """Poll entries from a feed."""
#     parser = feedparser.parse(feed.link)
# 
#     # Add entries from feed
#     entries = parser.entries
#     for entry in entries:
#         try:
#             published_parsed = entry.published_parsed
#         except AttributeError:  # an Atom feed
#             published_parsed = entry.updated_parsed
#         published = datetime.fromtimestamp(mktime(published_parsed))
#         try:
#             entry_obj, _ = Entry.objects.get_or_create(feed=feed,
#                                                        title=entry.title,
#                                                        link=entry.link,
#                                                        published=published)
#         except MultipleObjectsReturned:
#             pass
# 
#         subscribers = UserProfile.objects.filter(feeds=feed)
#         for profile in subscribers:
#             if not UserEntryDetail.objects.filter(entry=entry_obj,
#                                                   profile=profile)\
#                                           .exists():
#                 UserEntryDetail(entry=entry_obj,
#                                 profile=profile,
#                                 read=False).save()
# 
# Path: profiles/tasks.py
# @task
# def report_issue(summary, details):
#     gh = github.Github(settings.GITHUB_API_KEY)
#     repo = gh.get_repo("Nurdok/nextfeed")
#     repo.create_issue(summary, details)


import json
import feedparser
import time
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView, RedirectView, View
from django.views.generic.detail import DetailView
from django.http.response import HttpResponseRedirect, Http404, HttpResponseBadRequest
from profiles.forms import ReportForm
from profiles.models import UserProfile, UserEntryDetail, Subscription
from django.contrib.auth.models import User
from feeds.forms import FeedForm
from feeds.models import Feed, Entry
from django.views.generic.edit import FormView
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from feeds.tasks import poll_feed
from profiles.tasks import report_issue



class HomeView(TemplateView):
    template_name = 'home.html'


class AboutView(TemplateView):
    template_name = 'about.html'


class NoEntriesView(TemplateView):
    template_name = 'noentries.html'


class NextView(RedirectView):
    permanent = False

    def get_redirect_url(self, **kwargs):
        subscription = self.request.GET['subscription']
        try:

# Path: profiles/forms.py
# class ReportForm(forms.Form):
#     summary = forms.CharField(required=True,
#                               widget=forms.TextInput(attrs={'required': 'required',
#                                                             'class': 'form-control'}))
#     details = forms.CharField(widget=forms.Textarea, required=False)
# 
# Path: profiles/models.py
# class UserProfile(models.Model):
#     """A user profile."""
#     user = models.ForeignKey(User)
#     feeds = models.ManyToManyField(to=Feed, through='profiles.Subscription')
#     entries = models.ManyToManyField(to=Entry,
#                                      through='profiles.UserEntryDetail')
#     next_slug = RandomSlugField(slug_length=10)
# 
#     def __unicode__(self):
#         return u"{}'s profile".format(self.user.username)
# 
#     def subscribe(self, feed):
#         Subscription.objects.create(profile=self, feed=feed)
# 
#     def unsubscribe(self, feed):
#         Subscription.objects.get(profile=self, feed=feed).delete()
#         self._get_entries(feed).delete()
# 
#     def mark_read(self, feed):
#         entries = self._get_entries(feed)
#         for entry in entries:
#             entry.read = True
#             entry.save()
# 
#     def mark_unread(self, feed):
#         entries = self._get_entries(feed)
#         for entry in entries:
#             entry.read = False
#             entry.save()
# 
#     def unread_entries(self, feed):
#         return self._get_entries(feed).filter(read=False).count()
# 
#     def _get_entries(self, feed):
#         return UserEntryDetail.objects.filter(profile=self, entry__feed=feed)
# 
# class UserEntryDetail(models.Model):
#     profile = models.ForeignKey(to=UserProfile)
#     entry = models.ForeignKey(to=Entry)
#     read = models.BooleanField()
# 
#     def __unicode__(self):
#         return u'User: {}, Entry: {}, Read: {}'.format(
#                                                 self.profile.user.username,
#                                                 self.entry,
#                                                 self.read)
# 
# class Subscription(models.Model):
#     profile = models.ForeignKey(to=UserProfile)
#     feed = models.ForeignKey(to=Feed)
# 
#     def unread_entries_num(self):
#         unread_entries = UserEntryDetail.objects.filter(read=False,
#                                                         profile=self.profile,
#                                                         entry__feed=self.feed)
#         return unread_entries.count()
# 
# Path: feeds/forms.py
# class FeedForm(ModelForm):
#     class Meta:
#         model = Feed
#         fields = ['link']
#         widgets = {
#             'link': TextInput(attrs={'placeholder': 'Paste RSS address here!',
#                                      'id': 'feed-url-input'})
#         }
# 
#     def clean(self):
#         cleaned_data = super(FeedForm, self).clean()
#         parser = feedparser.parse(cleaned_data.get('link'))
#         if parser.feed == {} or parser.status != 200:
#             raise ValidationError("The link provided is not a valid feed.")
#         return cleaned_data
# 
# Path: feeds/models.py
# class Feed(models.Model):
#     title = models.CharField(max_length=200)
#     link = models.CharField(max_length=1000)
# 
#     def __unicode__(self):
#         return self.title
# 
# class Entry(models.Model):
#     title = models.CharField(max_length=200)
#     link = models.CharField(max_length=1000)
#     feed = models.ForeignKey(to=Feed)
#     published = models.DateTimeField()
# 
#     def __unicode__(self):
#         return u'{}: {}'.format(self.feed, self.title)
# 
# Path: feeds/tasks.py
# def poll_feed(feed):
#     """Poll entries from a feed."""
#     parser = feedparser.parse(feed.link)
# 
#     # Add entries from feed
#     entries = parser.entries
#     for entry in entries:
#         try:
#             published_parsed = entry.published_parsed
#         except AttributeError:  # an Atom feed
#             published_parsed = entry.updated_parsed
#         published = datetime.fromtimestamp(mktime(published_parsed))
#         try:
#             entry_obj, _ = Entry.objects.get_or_create(feed=feed,
#                                                        title=entry.title,
#                                                        link=entry.link,
#                                                        published=published)
#         except MultipleObjectsReturned:
#             pass
# 
#         subscribers = UserProfile.objects.filter(feeds=feed)
#         for profile in subscribers:
#             if not UserEntryDetail.objects.filter(entry=entry_obj,
#                                                   profile=profile)\
#                                           .exists():
#                 UserEntryDetail(entry=entry_obj,
#                                 profile=profile,
#                                 read=False).save()
# 
# Path: profiles/tasks.py
# @task
# def report_issue(summary, details):
#     gh = github.Github(settings.GITHUB_API_KEY)
#     repo = gh.get_repo("Nurdok/nextfeed")
#     repo.create_issue(summary, details)


# Path: profiles/views.py
import json
import feedparser
import time
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView, RedirectView, View
from django.views.generic.detail import DetailView
from django.http.response import HttpResponseRedirect, Http404, HttpResponseBadRequest
from profiles.forms import ReportForm
from profiles.models import UserProfile, UserEntryDetail, Subscription
from django.contrib.auth.models import User
from feeds.forms import FeedForm
from feeds.models import Feed, Entry
from django.views.generic.edit import FormView
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from feeds.tasks import poll_feed
from profiles.tasks import report_issue




class HomeView(TemplateView):
    template_name = 'home.html'


class AboutView(TemplateView):
    template_name = 'about.html'


class NoEntriesView(TemplateView):
    template_name = 'noentries.html'


class NextView(RedirectView):
    permanent = False

    def get_redirect_url(self, **kwargs):
        subscription = self.request.GET['subscription']
        try:

            profile = UserProfile.objects.get(next_slug=subscription)