# coding: utf-8

from __future__ import unicode_literals

from django import http

from cab.sources import oauth

import yenv

from cab.sources import staff_api


class WerewolfMiddleware(object):
    """
    Если зайти на урл /werewolf/<username>/ — поставится кука и
    аутентификация в остальных ручках будет происходить из-под
    пользователя <username>.

    Работает только после cab.utils.AuthMiddleware.
    """
    WEREWOLF_COOKIE = 'cab_werewolf'
    PATH_PREFIX = '/werewolf/'

    def process_request(self, request):
        is_enabled = yenv.choose_key_by_type({
            'testing': True,
            'production': False,
        }, fallback=True)
        if not is_enabled:
            return

        if request.path.startswith(self.PATH_PREFIX):
            return self.configure_werewolf(request)
        else:
            return self.release_werewolf(request)

    @staticmethod
    def _cut_port(host):
        if ':' in host:
            host, port = host.rsplit(':', 1)
        return host

    def get_cookie_domain(self, request):
        referer = request.META.get('HTTP_REFERER')
        if referer is not None:
            return self._cut_port(referer)
        else:
            return self._cut_port(request.META['HTTP_HOST'])

    def set_cookie(self, request, response, value):
        domain = self.get_cookie_domain(request)
        response.set_cookie(
            key=self.WEREWOLF_COOKIE,
            value=value,
            domain=domain
        )

    def delete_cookie(self, request, response):
        domain = self.get_cookie_domain(request)
        response.delete_cookie(key=self.WEREWOLF_COOKIE, domain=domain)

    def configure_werewolf(self, request):
        login = request.path[len(self.PATH_PREFIX):]
        login = login.rstrip('/')

        if login == '_clear':
            msg = 'Werewolf cookie deleted'
            response = http.JsonResponse({'msg': msg})
            self.delete_cookie(request, response)
        elif not login:
            login, uid = self.get_cookie_data(request=request)
            if login:
                msg = 'You are @%s' % login
                response = http.JsonResponse({'msg': msg})
            else:
                msg = " ".join([
                    'Set user at /werewolf/%username%/.',
                    'Delete werewolf cookie at /werewolf/_clear/.',
                ])
                response = http.JsonResponse({'msg': msg})
        else:
            msg = 'Pretending to be @' + login
            response = http.JsonResponse({'msg': msg})
            uid = staff_api.get_person_data(login=login)['uid']
            cookie_value = login + '|' + uid
            self.set_cookie(request, response, value=cookie_value)
        return response

    def release_werewolf(self, request):
        login, uid = self.get_cookie_data(request=request)
        if uid is None:
            return

        auth = request.auth
        # session_id остается реальный от смотрящего
        # auth.session_id = None
        # токен так получать больше невозможно
        # auth.oauth_token = oauth.get_token_by_uid(uid=uid)
        auth.uid = uid
        auth.login = login

    def get_cookie_data(self, request):
        werewolf_data = request.COOKIES.get(self.WEREWOLF_COOKIE)
        if werewolf_data is None:
            return None, None
        else:
            return werewolf_data.split('|')
