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

from django.utils.translation import ugettext_lazy as _

from events.geobase_contrib.client import GeobaseClient
from events.surveyme_integration.variables.base import BaseVariableCategory, BaseVariable

logger = logging.getLogger(__name__)


class GeobaseVariableCategory(BaseVariableCategory):
    name = 'geobase'
    title = _('Геобаза')
    order = 7


class GeobaseBaseVariable(BaseVariable):
    category = GeobaseVariableCategory()

    def get_region_by_id(self, region_id):
        client = GeobaseClient()
        try:
            return client.get_region_by_id(region_id)
        except Exception:
            logger.warn('Cannot found region %s', region_id)

    def get_region_by_ip(self, ip_address):
        client = GeobaseClient()
        try:
            return client.get_region_by_ip(ip_address)
        except Exception:
            logger.warn('Cannot found region with ip %s', ip_address)

    def get_region(self):
        region = None
        region_id = self.answer.source_request.get('x-geobase-id')
        if region_id:
            region = self.get_region_by_id(region_id)
        if not region:
            ip_address = self.answer.source_request.get('ip')
            region = self.get_region_by_ip(ip_address)
        return region


class GeobaseIdVariable(GeobaseBaseVariable):
    name = 'geobase.id'
    title = _('Код региона')

    def get_value(self, format_name=None):
        region = self.get_region()
        if region:
            return str(region['id'])


class GeobaseNameVariable(GeobaseBaseVariable):
    name = 'geobase.name'
    title = _('Имя региона')

    def get_lang(self):
        # accept-language: ru,en-US;q=0.7,en;q=0.3
        accept_language = self.answer.source_request.get('accept-language', 'ru')
        languages = [
            lang.split(';')[0]
            for lang in accept_language.split(',')
        ]
        return languages[0]

    def get_value(self, format_name=None):
        lang = self.get_lang()
        region = self.get_region()
        if region:
            return region['name'] if lang == 'ru' else region['en_name']
