from typing import Optional
from urllib.parse import quote

from .settings import (
    BLACKBOX_ATTRIBUTES, BLACKBOX_REAL_IP_HEADERS, BLACKBOX_SESSIONID2_REQUIRED, PASSPORT_TYPE, PASSPORT_URLS,
)


def get_real_ip(request):
    for header in BLACKBOX_REAL_IP_HEADERS:
        if header in request.META:
            return request.META[header].split(',')[0]
    return None


def get_current_host(request, drop_port=True):
    host = request.get_host()

    if drop_port:
        host = host.split(':')[0]

    return host


def get_passport_url(url_type, yauth_type=None, retpath=None):
    if url_type == 'create' and BLACKBOX_SESSIONID2_REQUIRED:
        url_type = 'create_secure'

    if yauth_type is None:
        yauth_type = PASSPORT_TYPE

    passport_url = PASSPORT_URLS[yauth_type][url_type]

    if retpath:
        passport_url += quote(retpath)

    return passport_url


def is_valid(session) -> bool:
    return session and session.get('status', {}).get('value', '') == 'VALID'


def is_secure(session) -> bool:
    return bool(session.get('auth', {}).get('secure', False))


def get_default_email(session) -> Optional[str]:
    address_list = session.get('address-list', [])
    if address_list:
        default_email = [a['address'] for a in address_list if a['default']] or [address_list[0]]
        return default_email.pop()
    return None


def get_uid(session) -> Optional[int]:
    uid = session.get('uid', {}).get('value')
    return int(uid) if uid else None


def get_attributes(session) -> Optional[dict]:
    attributes = session.get('attributes', [])
    return {BLACKBOX_ATTRIBUTES[k]: v for k, v in attributes.items()} if attributes else None
