# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _

from events.common_app.support.api_client import SupportAPIClient
from events.surveyme_integration.variables.base import BaseVariableCategory, BaseVariable


class SessionVariableCategory(BaseVariableCategory):
    name = 'session'
    title = _('Сессия')
    order = 8


class SessionBaseVariable(BaseVariable):
    what_to_get = None
    get_first_element_from_result = False
    category = SessionVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            feedback_sid = self.answer.source_request.get('feedback_sid')
            if feedback_sid:
                response = SupportAPIClient().get(
                    what=self.what_to_get,
                    params={'yandexuid': str(feedback_sid)}
                )
                if response:
                    if self.get_first_element_from_result:
                        response = response[0][self.what_to_get]
                    else:
                        response = ','.join(element[self.what_to_get] for element
                                            in response)
                    return response


class SessionRefererVariable(SessionBaseVariable):
    name = 'session.referer'
    title = _('Реферер')
    what_to_get = 'referer'
    get_first_element_from_result = True
