from django.http import HttpResponse

from staff.person.models import Staff
from staff.departments.models import Department

from staff.lib.json import dumps
from staff.lib.decorators import available_by_center_token

from . import ApiView


_def_dep_fields = ('id', 'name', 'code')
_full_dep_fields = ApiView.full_fields(Department)
_full_staff_fields = ApiView.full_fields(Staff)


@available_by_center_token
class DepartmentsView(ApiView):
    def prepare_data(self, *args, **kwargs):
        fields = self.get_fields(
            Department, 'fields', _def_dep_fields, _full_dep_fields, ['id', 'parent']
        )
        self.deps = (
            Department.objects
            .filter(intranet_status__gt=0)
            .order_by('tree_id', 'lft')
        )

        req_fields = self.request.GET.get('fields', self.request.POST.get('fields', ''))
        is_chief_field = req_fields.find('chief') != -1
        is_deputy_field = req_fields.find('deputy') != -1

        req_fields = self.request.GET.get('staff_fields', self.request.POST.get('staff_fields', None))
        is_staff_fields = req_fields is not None

        if is_chief_field or is_deputy_field:
            select = {}
            if is_chief_field:
                fields.append('chief')
                select['chief'] = (
                    'SELECT staff_id FROM intranet_departmentstaff'
                    ' WHERE '
                    ' intranet_departmentstaff.department_id=intranet_department.id'
                    ' AND intranet_departmentstaff.role_id=\'C\''
                )
            if is_deputy_field:
                fields.append('deputy')
                select['deputy'] = (
                    'SELECT staff_id FROM intranet_departmentstaff'
                    ' WHERE '
                    ' intranet_departmentstaff.department_id=intranet_department.id'
                    ' AND intranet_departmentstaff.role_id=\'D\''
                )
            self.deps = self.deps.extra(select=select)
        self.deps = self.deps.values(*fields)

        if is_staff_fields:
            staff_fields = self.get_fields(
                Staff, 'staff_fields', ('id', 'login'), _full_staff_fields, ['id', 'login']
            )

            for d in self.deps:
                d['_users'] = list(
                    Staff.objects
                    .values(*staff_fields)
                    .filter(department=Department.objects.get(pk=d['id']))
                    .filter(is_dismissed=False)
                )

    def render_json(self):
        res = []
        parents = [res]
        for d in self.deps:
            while len(parents) > 1 and d['parent'] != parents[-1]['id']:
                parents.pop()
            if len(parents) > 1:
                if '_departments' not in parents[-1]:
                    parents[-1]['_departments'] = []
                parents[-1]['_departments'].append(d)
            else:
                parents[-1].append(d)
            parents.append(d)
        return HttpResponse(dumps(res), content_type='text/javascript')
