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

from events.surveyme_integration.variables.base import BaseVariableCategory, BaseVariable


class RequestVariableCategory(BaseVariableCategory):
    name = 'request'
    title = _('Запрос')
    order = 5


class RequestVariableFromName(BaseVariable):
    source_key = None
    category = RequestVariableCategory()
    arguments = ['name']

    def __init__(self, name=None, **kwargs):
        super(RequestVariableFromName, self).__init__(**kwargs)
        self.name = name

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get(self.source_key, {}).get(self.name.lower())


class RequestIpVariable(BaseVariable):
    name = 'request.ip'
    title = _('IP-адрес')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if not settings.IS_BUSINESS_SITE:
            if self.answer.source_request:
                return self.answer.source_request.get('ip')


class RequestHostVariable(BaseVariable):
    name = 'request.host'
    title = _('Хост')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get('headers', {}).get('host')


class RequestURLVariable(BaseVariable):
    name = 'request.url'
    title = _('URL')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get('url')


class RequestHeadersVariable(BaseVariable):
    name = 'request.headers'
    title = _('Все заголовки')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get('headers')


class RequestHeaderVariable(RequestVariableFromName):
    name = 'request.header'
    title = _('Заголовок')
    source_key = 'headers'


class RequestQueryParamsVariable(BaseVariable):
    name = 'request.query_params'
    title = _('Все GET-параметры')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get('query_params')


class RequestQueryParamVariable(RequestVariableFromName):
    name = 'request.query_param'
    title = _('GET-параметр')
    source_key = 'query_params'


class RequestCookiesVariable(BaseVariable):
    name = 'request.cookies'
    title = _('Все куки')
    category = RequestVariableCategory()

    def get_value(self, format_name=None):
        if self.answer.source_request:
            return self.answer.source_request.get('cookies')


class RequestCookieVariable(RequestVariableFromName):
    name = 'request.cookie'
    title = _('Кука')
    source_key = 'cookies'
