from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LogoutView
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
from .models import *
from .forms import *


class HomePageListView(ListView):
    model = Service
    template_name = 'main_page.html'
    context_object_name = 'services'

    def get_queryset(self):
        return Service.objects.order_by('-publish_date')[:5]


class ServicesListView(ListView):
    model = Service
    template_name = 'services.html'
    context_object_name = 'services'


class ServiceDetailView(DetailView):
    model = Service
    template_name = 'service.html'


class UserProfileView(LoginRequiredMixin, ListView):
    model = OrderedService
    template_name = 'profile.html'
    context_object_name = 'ordered_services'

    def get_queryset(self):
        return OrderedService.objects.filter(user=self.request.user)


class SignupView(CreateView):
    form_class = SignupForm
    model = AdvUser
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('login')


class BBLogoutView(LogoutView):
    template_name = 'registration/logout.html'


@login_required
def add_to_cart(request, service_id):
    service = Service.objects.get(id=service_id)
    OrderedService.objects.create(service=service, user=request.user)

    return HttpResponseRedirect(reverse_lazy('service', args=(service.id,)))


def search(request):
    query = request.GET.get('search')
    services = Service.objects.filter(name__icontains=query)
    return render(request, 'search_result.html', {'services': services})
