from .models import Project
from core.views import ModelListViewBase, DetailedModelViewBase, SimpleCreateViewBase, SimpleUpdateViewBase
from clients.models import ClientOffice
from django.core.exceptions import ObjectDoesNotExist
from rest.serializers import ProjectsSerializer
from users.access_checks import LoginRequiredMixin
from users.models import LAB_GROUP_ID


class ProjectsListView(LoginRequiredMixin, ModelListViewBase):
    serializer = ProjectsSerializer
    require_group = LAB_GROUP_ID

    def get_query(self):
        # prefetch client for office, which speeds up the __str__ method of the office
        return Project.objects.all().prefetch_related('client', 'client__client')


class ProjectDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = Project
    template_name = 'projects/project_detail.html'

    require_group = LAB_GROUP_ID


class ProjectCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = Project

    require_group = LAB_GROUP_ID

    def get_initial(self):
        initial = super(ProjectCreateView, self).get_initial()
        try:
            # check if we got called from a office view, which adds auto adds
            # the contact person and the client field
            office_id = self.request.GET.get('office', 0)
            office_instance = ClientOffice.objects.get(pk=office_id)
            # note: this is the implicit 'case' if the get succeeded, which only
            # will fail if you manually type a wrong pk into the url.
            initial['client'] = office_id
            # check if we reuse the contact for this office for the project too.
            if office_instance.contact:
                initial['contact'] = office_instance.contact_id
        except ValueError:  # silently fail if a hand typed url provides rubbish
            pass
        except ObjectDoesNotExist:
            pass
        return initial


class ProjectUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = Project
    require_group = LAB_GROUP_ID
