import logging

from django.conf import settings

from staff.lib.blackbox import Blackbox

from staff.person.models import AFFILIATION
from staff.person.passport.base import BBField, Passport

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


def sid_668_to_bb(value, instance):
    return {} if value else None


def sid_669_to_bb(value, instance):
    return {'yastaff_login': instance.int_login} if value else None


class ExtPassport(Passport):
    blackbox = Blackbox(
        blackbox_url=settings.EXT_BLACKBOX_URL,
        service_name='ext_blackbox',
    )
    PASSPORT_URL = settings.EXT_PASSPORT_URL
    PASSPORT_PATH = '/1/account/{uid}/subscription/{service_slug}/'
    TIMEOUT = 5

    def __init__(self, ext_login, int_login):
        self.ext_login = ext_login
        self.int_login = int_login
        uid = self.blackbox.get_uid_by_login(ext_login)
        super(ExtPassport, self).__init__(uid)

    sid_668 = BBField(
        passport_name='betatest',
        passport_field='subscription.suid.668',
        from_bb=bool,
        to_bb=sid_668_to_bb,
    )
    sid_669 = BBField(
        passport_name='yastaff',
        passport_field='subscription.suid.669',
        from_bb=bool,
        to_bb=sid_669_to_bb,
    )

    def upload_bb_data(self):
        for passport_name, value in self.for_update.items():
            self.push_to_passport(value, service_slug=passport_name)

        self.for_update = {}


def login_has_sid_668(ext_login):
    return bool(not ext_login.person.is_dismissed and ext_login.status_active)


def login_has_sid_669(ext_login):
    return bool(
        login_has_sid_668(ext_login) and
        ext_login.person.affiliation in (AFFILIATION.YANDEX, AFFILIATION.YAMONEY)
    )


def sync_with_external_passport(ext_login):
    logger.info(
        'Sync ExtPassport for %s and external login %s',
        ext_login.person.login,
        ext_login.login,
    )

    ext_passport = ExtPassport(ext_login.login, ext_login.person.login)
    ext_passport.sid_668 = login_has_sid_668(ext_login)
    ext_passport.sid_669 = login_has_sid_669(ext_login)
    ext_passport.save()


def try_to_get_actual_login(staff_login: str):
    try:
        return ExtPassport.blackbox.get_user_info(
            login=staff_login,
            sid=669,
        )['fields']['aliases'][0][1]
    except Exception:
        return None
