from django.views.generic import ListView, DetailView
from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth import logout
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Podcast, PodcastPart


def logout_view(request):
    if request.user.is_authenticated():
        logout(request)
        return redirect('welcome:index')
    else:
        return redirect('podcast:podcasts')


class IndexView(LoginRequiredMixin, ListView):
    login_url = 'welcome:index'
    template_name = 'podcasts.html'
    context_object_name = 'all_podcasts'

    def get_queryset(self):
        return Podcast.objects.all()


class PodcastView(LoginRequiredMixin, DetailView):
    login_url = 'welcome:index'
    model = Podcast
    template_name = 'podcast_detail.html'

    def get_context_data(self, **kwargs):
        context = super(PodcastView, self).get_context_data(**kwargs)
        context['part_list'] = PodcastPart.objects.filter(podcast=self.object).order_by('id')
        return context


