import logging
from datetime import datetime

from django.conf import settings

from staff.lib.blackbox import Blackbox

from staff.person.passport.base import BBField, Passport, PassportException

logger = logging.getLogger('staff.passport')


class IntPassport(Passport):
    blackbox = Blackbox(
        blackbox_url=settings.BLACKBOX_URL,
        service_name='blackbox',
    )
    PASSPORT_URL = settings.INT_PASSPORT_URL
    PASSPORT_PATH = '/1/bundle/account/person/'
    LOGOUT_PATH = '/2/account/{uid}/password_options/'
    BLOCK_PATH = '/1/account/{uid}/'
    TIMEOUT = 5

    tz = BBField(
        passport_name='timezone',
    )
    birthday = BBField(
        passport_name='birthday',
        to_bb=lambda v: v.isoformat() if v else '0000-00-00',
        from_bb=lambda v: datetime.strptime(v, '%Y-%m-%d').date() if v else v,
    )
    first_name = BBField(
        passport_name='firstname',
        to_bb=lambda v: v.encode('utf-8'),
    )
    last_name = BBField(
        passport_name='lastname',
        to_bb=lambda v: v.encode('utf-8'),
    )
    first_name_en = BBField(
        passport_name='firstname_global',
        to_bb=lambda v: v.encode('utf-8'),
    )
    last_name_en = BBField(
        passport_name='lastname_global',
        to_bb=lambda v: v.encode('utf-8'),
    )
    lang_ui = BBField(
        passport_name='language',
    )
    gender = BBField(
        passport_name='gender',
        to_bb={'M': 'm', 'F': 'f'}.get,
        from_bb={'1': 'M', '2': 'F'}.get,
    )

    def push_passport_path(self, **kwargs):
        return self.PASSPORT_URL + self.PASSPORT_PATH

    def upload_bb_data(self):
        self.for_update['uid'] = self.uid
        self.push_to_passport(self.for_update)
        self.for_update = {}

    def logout(self):
        logger.info('Global logout for passport {uid}'.format(uid=self.uid))
        url = self.PASSPORT_URL + self.LOGOUT_PATH.format(uid=self.uid)
        self._passport_api_request('post', url, {'global_logout': True})

    def block(self):
        logger.info('Block for passport {uid}'.format(uid=self.uid))
        url = self.PASSPORT_URL + self.BLOCK_PATH.format(uid=self.uid)
        self._passport_api_request('post', url, {'is_enabled': False})

    def unblock(self):
        logger.info('Unblock for passport {uid}'.format(uid=self.uid))
        url = self.PASSPORT_URL + self.BLOCK_PATH.format(uid=self.uid)
        self._passport_api_request('post', url, {'is_enabled': True})


def sync_with_internal_passport(person):
    try:
        int_passport = IntPassport(person.uid)

        fields = [
            'tz',
            'birthday',
            'first_name',
            'last_name',
            'first_name_en',
            'last_name_en',
            'lang_ui',
            'gender',
        ]

        for field in fields:
            person_value = getattr(person, field)
            # заплатка, пока не решим https://st.yandex-team.ru/STAFF-4055
            if field == 'birthday' and person_value is None:
                continue
            setattr(int_passport, field, person_value)

        int_passport.save()
    except PassportException:
        pass
