# Path: profiles/views.py
# class NextView(RedirectView):
#     permanent = False
# 
#     def get_redirect_url(self, **kwargs):
#         subscription = self.request.GET['subscription']
#         try:
#             profile = UserProfile.objects.get(next_slug=subscription)
#         except Exception:
#             raise Http404()
#         entries = profile.entries.filter(userentrydetail__read=False)
#         if not entries.exists():
#             return '/noentries'
#         print entries.order_by('published')
#         entry = entries.order_by('published')[0]
#         user_entry = entry.userentrydetail_set.get(profile=profile)
#         user_entry.read = True
#         user_entry.save()
#         return entry.link
# 
# class DashboardView(FormView):
#     template_name = 'dashboard.html'
#     form_class = FeedForm
#     success_url = '/dashboard'
# 
#     def form_valid(self, form):
#         user = self.request.user
#         link = form.cleaned_data['link']
#         if not link.startswith('http://'):
#             link = 'http://{}'.format(link)
#         parser = feedparser.parse(link)
#         feed = parser.feed
#         title = feed.title
#         try:
#             feed_obj = Feed.objects.get(link=link)
#         except ObjectDoesNotExist:
#             feed_obj = Feed(link=link, title=title)
#             feed_obj.save()
#         profile = user.get_profile()
#         Subscription(profile=profile, feed=feed_obj).save()
#         poll_feed(feed_obj)
#         return super(DashboardView, self).form_valid(form)
# 
#     def get_context_data(self, *args, **kwargs):
#         user = self.request.user
#         try:
#             user.get_profile()
#         except:
#             UserProfile(user=user).save()
#         context = super(DashboardView, self).get_context_data(*args, **kwargs)
#         subscriptions = Subscription.objects.filter(profile=user.get_profile())
#         context['subscriptions'] = subscriptions
#         return context
# 
# class HomeView(TemplateView):
#     template_name = 'home.html'
# 
# class NoEntriesView(TemplateView):
#     template_name = 'noentries.html'
# 
# class AboutView(TemplateView):
#     template_name = 'about.html'
# 
# class MarkUnreadView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().mark_unread(feed)
#         return super(MarkUnreadView, self).dispatch(request, *args, **kwargs)
# 
# class MarkReadView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().mark_read(feed)
#         return super(MarkReadView, self).dispatch(request, *args, **kwargs)
# 
# class UnsubscribeView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().unsubscribe(feed)
#         return super(UnsubscribeView, self).dispatch(request, *args, **kwargs)
# 
# def subscription(request):
#     profile = request.user.get_profile()
#     if request.method == "GET":
#         subscriptions = Subscription.objects.filter(profile=profile)
#         subscriptions_json = [{'id': s.feed.id,
#                                'title': s.feed.title,
#                                'unread_entries': profile.unread_entries(s.feed)}
#                               for s in subscriptions]
#         return HttpResponse(json.dumps(subscriptions_json),
#                             content_type='application/json')
#     if request.method == "POST":
#         link = json.loads(request.body)['link']
#         if not link.startswith('http://'):
#             link = 'http://{}'.format(link)
#         parser = feedparser.parse(link)
#         feed = parser.feed
#         try:
#             title = feed.title
#         except AttributeError:
#             return HttpResponseBadRequest('Invalid feed')
#         try:
#             feed_obj = Feed.objects.get(link=link)
#         except ObjectDoesNotExist:
#             feed_obj = Feed(link=link, title=title)
#             feed_obj.save()
#         if Subscription.objects.filter(profile=profile, feed=feed_obj).exists():
#             return HttpResponseBadRequest('You are already subscribed to this '
#                                           'feed')
#         Subscription.objects.get_or_create(profile=profile, feed=feed_obj)
#         try:
#             poll_feed(feed_obj)
#         except AttributeError:
#             return HttpResponseBadRequest('Invalid feed')
#         return HttpResponse()
# 
# class ReportView(TemplateView):
# 
#     def post(self, request):
#         data = json.loads(request.body)
#         report_form = ReportForm({'summary': data[u'summary'],
#                                   'details': data[u'details']})
#         if report_form.is_valid():
#             report_issue(report_form.cleaned_data['summary'],
#                          report_form.cleaned_data['details'])
#         else:
#             return HttpResponseBadRequest('Form was invalid: {}'.format(report_form.errors))
#         return HttpResponse("Report was submitted!")


from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.contrib import admin
from profiles.views import (NextView, DashboardView, HomeView, NoEntriesView,
                            AboutView, MarkUnreadView, MarkReadView,
                            UnsubscribeView, subscription, ReportView)

# Uncomment the next two lines to enable the admin:
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', HomeView.as_view(), name="home"),
    url(r'^openid/?', include('django_openid_auth.urls')),
    url(r'^admin/?', include(admin.site.urls)),
    url(r'^next/?', login_required(NextView.as_view())),

# Path: profiles/views.py
# class NextView(RedirectView):
#     permanent = False
# 
#     def get_redirect_url(self, **kwargs):
#         subscription = self.request.GET['subscription']
#         try:
#             profile = UserProfile.objects.get(next_slug=subscription)
#         except Exception:
#             raise Http404()
#         entries = profile.entries.filter(userentrydetail__read=False)
#         if not entries.exists():
#             return '/noentries'
#         print entries.order_by('published')
#         entry = entries.order_by('published')[0]
#         user_entry = entry.userentrydetail_set.get(profile=profile)
#         user_entry.read = True
#         user_entry.save()
#         return entry.link
# 
# class DashboardView(FormView):
#     template_name = 'dashboard.html'
#     form_class = FeedForm
#     success_url = '/dashboard'
# 
#     def form_valid(self, form):
#         user = self.request.user
#         link = form.cleaned_data['link']
#         if not link.startswith('http://'):
#             link = 'http://{}'.format(link)
#         parser = feedparser.parse(link)
#         feed = parser.feed
#         title = feed.title
#         try:
#             feed_obj = Feed.objects.get(link=link)
#         except ObjectDoesNotExist:
#             feed_obj = Feed(link=link, title=title)
#             feed_obj.save()
#         profile = user.get_profile()
#         Subscription(profile=profile, feed=feed_obj).save()
#         poll_feed(feed_obj)
#         return super(DashboardView, self).form_valid(form)
# 
#     def get_context_data(self, *args, **kwargs):
#         user = self.request.user
#         try:
#             user.get_profile()
#         except:
#             UserProfile(user=user).save()
#         context = super(DashboardView, self).get_context_data(*args, **kwargs)
#         subscriptions = Subscription.objects.filter(profile=user.get_profile())
#         context['subscriptions'] = subscriptions
#         return context
# 
# class HomeView(TemplateView):
#     template_name = 'home.html'
# 
# class NoEntriesView(TemplateView):
#     template_name = 'noentries.html'
# 
# class AboutView(TemplateView):
#     template_name = 'about.html'
# 
# class MarkUnreadView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().mark_unread(feed)
#         return super(MarkUnreadView, self).dispatch(request, *args, **kwargs)
# 
# class MarkReadView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().mark_read(feed)
#         return super(MarkReadView, self).dispatch(request, *args, **kwargs)
# 
# class UnsubscribeView(EditEntriesForFeedView):
#     def dispatch(self, request, *args, **kwargs):
#         feed = self._get_feed()
#         self.request.user.get_profile().unsubscribe(feed)
#         return super(UnsubscribeView, self).dispatch(request, *args, **kwargs)
# 
# def subscription(request):
#     profile = request.user.get_profile()
#     if request.method == "GET":
#         subscriptions = Subscription.objects.filter(profile=profile)
#         subscriptions_json = [{'id': s.feed.id,
#                                'title': s.feed.title,
#                                'unread_entries': profile.unread_entries(s.feed)}
#                               for s in subscriptions]
#         return HttpResponse(json.dumps(subscriptions_json),
#                             content_type='application/json')
#     if request.method == "POST":
#         link = json.loads(request.body)['link']
#         if not link.startswith('http://'):
#             link = 'http://{}'.format(link)
#         parser = feedparser.parse(link)
#         feed = parser.feed
#         try:
#             title = feed.title
#         except AttributeError:
#             return HttpResponseBadRequest('Invalid feed')
#         try:
#             feed_obj = Feed.objects.get(link=link)
#         except ObjectDoesNotExist:
#             feed_obj = Feed(link=link, title=title)
#             feed_obj.save()
#         if Subscription.objects.filter(profile=profile, feed=feed_obj).exists():
#             return HttpResponseBadRequest('You are already subscribed to this '
#                                           'feed')
#         Subscription.objects.get_or_create(profile=profile, feed=feed_obj)
#         try:
#             poll_feed(feed_obj)
#         except AttributeError:
#             return HttpResponseBadRequest('Invalid feed')
#         return HttpResponse()
# 
# class ReportView(TemplateView):
# 
#     def post(self, request):
#         data = json.loads(request.body)
#         report_form = ReportForm({'summary': data[u'summary'],
#                                   'details': data[u'details']})
#         if report_form.is_valid():
#             report_issue(report_form.cleaned_data['summary'],
#                          report_form.cleaned_data['details'])
#         else:
#             return HttpResponseBadRequest('Form was invalid: {}'.format(report_form.errors))
#         return HttpResponse("Report was submitted!")


# Path: nextfeed/urls.py
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.contrib import admin
from profiles.views import (NextView, DashboardView, HomeView, NoEntriesView,
                            AboutView, MarkUnreadView, MarkReadView,
                            UnsubscribeView, subscription, ReportView)


# Uncomment the next two lines to enable the admin:
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', HomeView.as_view(), name="home"),
    url(r'^openid/?', include('django_openid_auth.urls')),
    url(r'^admin/?', include(admin.site.urls)),
    url(r'^next/?', login_required(NextView.as_view())),

    url(r'^dashboard/?$', login_required(DashboardView.as_view()), name="dashboard"),