from django.shortcuts import render, redirect
# from django.contrib.auth.decorators import login_required
from django.views.generic import ListView, CreateView, DetailView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Customer
from django.db import connection

# @login_required
# def customers_list(request):
#     context = {
#         'customers': Customer.objects.all()
#     }
#     return render(request, 'customers/home.html', context)


class CustomersListView(LoginRequiredMixin, ListView):
    model = Customer
    template_name = 'customers/home.html'
    context_object_name = 'customers'


class CustomersDetailView(LoginRequiredMixin, DetailView):
    model = Customer


# class CustomersCreateView(LoginRequiredMixin, CreateView):
#     model = Customer
#     fields = ['last_name', 'first_name', 'email', 'address', 'birthday', 'phone']
#
#     def get_form(self):
#         from django.forms.widgets import SelectDateWidget
#         form = super(CustomersCreateView, self).get_form()
#         form.fields['birthday'].widget = SelectDateWidget()
#         return form

class CustomersCreateView(LoginRequiredMixin, CreateView):
    model = Customer
    fields = ['last_name', 'first_name', 'email', 'address', 'birthday', 'phone']

    def post(self, request, *args, **kwargs):
        last_name = self.request.POST.get("last_name")
        first_name = self.request.POST.get("first_name")
        email = self.request.POST.get("email")
        address = self.request.POST.get("address")
        birthday = f'{self.request.POST.get("birthday_year")}-{self.request.POST.get("birthday_month")}' \
                   f'-{self.request.POST.get("birthday_day")}'
        phone = self.request.POST.get("phone")
        cursor = connection.cursor()
        query = "INSERT INTO customers_customer (last_name, first_name, email, address, birthday, " \
                "phone) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" \
                % (last_name, first_name, email, address, birthday, phone)
        result = cursor.execute(query)
        return redirect('customer-detail', result.lastrowid)

    def get_form(self, form_class=None):
        from django.forms.widgets import SelectDateWidget
        form = super(CustomersCreateView, self).get_form()
        form.fields['birthday'].widget = SelectDateWidget()
        return form


class CustomersUpdateView(LoginRequiredMixin, UpdateView):
    model = Customer
    fields = ['last_name', 'first_name', 'email', 'address', 'birthday', 'phone']

    def get_form(self, form_class=None):
        from django.forms.widgets import SelectDateWidget
        form = super(CustomersUpdateView, self).get_form()
        form.fields['birthday'].widget = SelectDateWidget()
        return form
