from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views import generic
from django.shortcuts import HttpResponseRedirect
from django.contrib.auth import logout

from .models import *
from .forms import *


# Create your views here.
class Main(generic.ListView):
    model = Product
    context_object_name = 'products'
    template_name = 'mainapp/index.html'

    def get_queryset(self):
        return Product.objects.all()[:5]

@login_required
def profile(request):
    order = Order.objects.filter(user=request.user)
    context = {
        "orders": order,
    }
    return render(request, 'mainapp/profile.html', context)


class ServiceList(generic.ListView):
    model = Product
    context_object_name = 'products'
    template_name = 'mainapp/services.html'

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


def service_detail(request, id):
    product = get_object_or_404(Product, id=id)
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.product_id = id
            instance.save()
    else:
        form = OrderForm(initial={'user': request.user.pk, 'product': id})
    return render(request, "mainapp/service_detail.html", {'product': product, 'form': form})


class RegisterView(generic.CreateView):
    model = CustomUser
    form_class = RegisterForm
    template_name = 'mainapp/register.html'
    success_url = reverse_lazy('login')


def logoutUser(request):
   logout(request)
   return HttpResponseRedirect('/')