from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView, TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from .models import Video, Channel, Category, LiveStream
from .forms import VideoUploadForm

class IndexView(ListView):
    model = Video
    template_name = 'core/index.html'
    context_object_name = 'videos'
    paginate_by = 20

    def get_queryset(self):
        return Video.objects.filter(is_published=True, video_type='standard').select_related('channel')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        context['shorts'] = Video.objects.filter(video_type='short', is_published=True)[:10]
        return context

class VideoDetailView(DetailView):
    model = Video
    template_name = 'core/video_detail.html'
    context_object_name = 'video'

    def get_object(self):
        obj = super().get_object()
        obj.views += 1
        obj.save()
        return obj

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['related_videos'] = Video.objects.filter(category=self.object.category).exclude(id=self.object.id)[:10]
        return context

class ShortsListView(ListView):
    model = Video
    template_name = 'core/shorts_list.html'
    context_object_name = 'shorts'

    def get_queryset(self):
        return Video.objects.filter(video_type='short', is_published=True)

class LiveStudioView(LoginRequiredMixin, TemplateView):
    template_name = 'core/live_studio.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        channel = getattr(self.request.user, 'channel', None)
        if channel:
            context['live_streams'] = LiveStream.objects.filter(channel=channel)
            context['videos'] = Video.objects.filter(channel=channel)
        return context

class UploadVideoView(LoginRequiredMixin, CreateView):
    model = Video
    form_class = VideoUploadForm
    template_name = 'core/upload_video.html'
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        # Ensure user has a channel
        channel, created = Channel.objects.get_or_create(
            user=self.request.user,
            defaults={'name': self.request.user.username, 'handle': self.request.user.username.lower()}
        )
        form.instance.channel = channel
        return super().form_valid(form)

def home(request):
    return IndexView.as_view()(request)
