# -*- coding: utf-8 -*-
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


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

    def extract_params(self, request):
        params = super().extract_params(request)
        if not params:
            return params

        params['request'] = request
        return params

    def apply(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        yauser = super().apply(*args, **kwargs)
        if isinstance(yauser, self.YandexUser):
            yauser.orgs = request.orgs
        return yauser
