from staff.lib.exceptions import ErrorWithStatusCode

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

from staff.person.controllers import PersonCtl
from staff.person_profile.errors import log_does_not_exist_staff_login

import logging
logger = logging.getLogger('person_profile.controllers.department')


class DepartmentError(ErrorWithStatusCode):
    pass


def get_initial(login):
    with log_does_not_exist_staff_login(logger=logger, message_params=[login], raise_e=DepartmentError):
        return (
            Staff.objects
            .values(
                'department__id',
                'department__name',
                'department__name_en',
            ).get(login=login)
        )


def update(login, data, request_user):
    with log_does_not_exist_staff_login(logger=logger, message_params=[login], raise_e=DepartmentError):
        person = Staff.objects.get(login=login)

    ctl = PersonCtl(person)
    ctl.department = Department.objects.get(id=data['department_id'])
    ctl.save(request_user)
