from django.shortcuts import redirect
from django.views.generic import TemplateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from ..models import Distributor
from django.core.paginator import Paginator
from django.db.models import ProtectedError
from ..forms import *
from django.db.models import Q
from .generic_views import BaseTemplateMixin

class DistributorView(LoginRequiredMixin, BaseTemplateMixin, TemplateView):
    template_name = 'parts/distributors.html'
    base_title = 'Distributors'
    navbar_selected = 'Distributors'
    default_page_size = 25

    def search_distributors(self, search):
        qs = Distributor.objects.all()

        if not search:
            return qs

        search_fragments = search.strip().split()

        for search in search_fragments:
            qs = qs.filter(Q(name__icontains = search) | Q(website__icontains = search))
        return qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        page_num = self.request.GET.get('page', default=1)
        search_string = self.request.GET.get('search', default=None)

        queryset = self.search_distributors(search_string)

        paginator = Paginator(queryset, self.default_page_size)


        context['search_string'] = search_string
        context['distributors'] = paginator.get_page(page_num)
        context['new_distri_form'] = DistributorForm()

        return context

    def handle_add_new_distributor(self, request):

        form = DistributorForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            form.save()

        context = self.get_context_data()

        if not form.is_valid():
            context['new_distri_form'] = form

        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if 'submit-distri-add-new' in request.POST:
            return self.handle_add_new_distributor(request)

        return super().post(request, *args, **kwargs)


class DistributorDetailView(LoginRequiredMixin, BaseTemplateMixin, DetailView):
    template_name = 'parts/distributors-detail.html'
    model = Distributor
    pk_url_kwarg = 'uuid'
    base_title = ''
    navbar_selected = 'Distributors'

    def get_context_data(self, **kwargs):
        self.base_title = 'Distributor / '+self.object.name
        context = super().get_context_data(**kwargs)
        context['distributor'] = self.object
        context['edit_form'] = DistributorForm(instance=self.object)

        return context

    def handle_delete_distributor(self, request):
        delete_error = None
        protected_objects = None

        # Try to delete this instance
        try:
            self.object.delete()
        except ProtectedError as pe:
            delete_error = 'Cannot delete this distributor. It is referenced by a component.'
            protected_objects = pe.protected_objects
        except:
            delete_error = 'Cannot delete this distributor. Unknown error'

        if delete_error:
            context = self.get_context_data()
            context['delete_error'] = delete_error
            context['protected_components'] = protected_objects
            return self.render_to_response(context)
        else:
            return redirect('parts-distributors')

    def edit_distributor(self, request):
        edit_form = DistributorForm(data=request.POST, files=request.FILES, instance=self.object)

        if edit_form.is_valid():
            edit_form.save()

        context = self.get_context_data()
        if not edit_form.is_valid():
            context['edit_form'] = edit_form
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        if 'submit-distri-delete' in request.POST:
            return self.handle_delete_distributor(request)
        elif 'submit-distri-edit' in request.POST:
            return self.edit_distributor(request)

        return super().post(request, *args, **kwargs)
