from logging import getLogger

import json
import re

import tornado
from django.utils.encoding import force_text


log = getLogger(__name__)


def has_digits(text):
    return bool(re.search(r'\d', text))


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Exception):
            return force_text(o)
        else:
            return super().default(o)


def translate(phrase, state):
    user_locale = tornado.locale.get(state.language)
    return str(user_locale.translate(phrase))


def get_client_ip(request):
    x_forwarded_for = request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.headers.get('X-Real-Ip') or request.remote_ip
    return ip


def get_request_id(request, default=''):
    return request.headers.get('X-Req-Id') or request.headers.get('X-Request-Id') or default


def string_to_bool(value):
    return bool(string_to_int(value))


def string_to_int(value):
    try:
        return int(value or 0)
    except ValueError:
        return 0


def split_to_int_list(value, separator=','):
    if not value:
        return []

    return [int(v.strip()) for v in value.split(separator)]
