# -*- coding: utf-8 -*-
import logging

from django_yauth.authentication_mechanisms.cookie import Mechanism as BaseMechanism

from events.yauth_contrib.user import FormsCookieYandexUser, FormsAnonymousYandexUser
from events.yauth_contrib.mechanisms.base import BaseFormsMixin

logger = logging.getLogger(__name__)


def get_authorization_header(request):
    """Example
    GET .resource HTTP.1.1
    Host: service.yandex.ru
    Authorization: OAuth vF9dft4qmT
    """
    return request.META.get('HTTP_AUTHORIZATION', '')


def get_authorization_token(name, request):
    """Example
    Authorization: OAuth vF9dft4qmT
    Authorization: SessionId vF9dft4qmT
    """
    try:
        found_name, token = get_authorization_header(request).split(' ')
    except ValueError:
        return None

    if name.lower() == found_name.lower():
        return token
    else:
        return None


class Mechanism(BaseFormsMixin, BaseMechanism):
    YandexUser = FormsCookieYandexUser
    AnonymousYandexUser = FormsAnonymousYandexUser

    def _get_session_id(self, request):
        return get_authorization_token('sessionid', request)
