from django.core.exceptions import ObjectDoesNotExist

from staff.lib.exceptions import ErrorWithStatusCode

from staff.person.models import Staff

from staff.innerhire.models import Candidate
from staff.innerhire.utils import update_candidate_info
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.duties')


class DutiesError(ErrorWithStatusCode):
    pass


def get_duties_initial(login):
    result = {}
    with log_does_not_exist_staff_login(logger=logger, message_params=[login], raise_e=DutiesError):
        result.update(
            Staff.objects
            .values('duties', 'duties_en')
            .get(login=login)
        )

    try:
        result['candidate_info'] = (
            Candidate.objects
            .values_list('description_source', flat=True)
            .get(person__login=login, date_close=None)
        )
    except ObjectDoesNotExist:
        pass

    return result


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

    person_data = {
        'duties': data.get('duties', ''),
        'duties_en': data.get('duties_en', ''),
    }
    PersonCtl(person).update(person_data).save(request_user)
    update_candidate_info(
        person,
        data['candidate_info'],
        request_user.get_profile(),
    )
