from staff.lib.exceptions import ErrorWithStatusCode

from staff.person.models import Staff

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.location')


class LocationError(ErrorWithStatusCode):
    pass


class LocationCtl(object):
    def __init__(self, login):
        self.login = login

    def get_location_initial(self):
        with log_does_not_exist_staff_login(logger=logger, message_params=[self.login], raise_e=LocationError):
            return (
                Staff.objects.values(
                    'location_descr',
                    'location_descr_en',
                )
                .get(login=self.login)
            )

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

        try:
            PersonCtl(person).update(data).save(request_user)
        except Exception:
            logger.exception(
                'Error trying to update person with login %s',
                self.login
            )
            raise LocationError('cannot-update-location')
