# general utils
try:
    import hashlib
except ImportError:
    import md5 as hashlib
import itertools
import logging
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from django.utils.encoding import smart_unicode
from django.core.cache import cache
from django.core.urlresolvers import reverse

from urlparse import urlparse, urlunparse

try:
    from functools import update_wrapper, wraps
except ImportError:
    from django.utils.functional import update_wrapper, wraps  # Python 2.3, 2.4 fallback.


def log(msg):
    if settings.DEBUG:
        logging.info(" Arecibo: %s" % msg)


def safe_int(key, result=None):
    try:
        return int(key)
    except (ValueError, AttributeError):
        return result


def render_plain(msg):
    return HttpResponse(msg, mimetype="text/plain")


def render_json(view_func):
    def wrapper(*args, **kwargs):
        data = view_func(*args, **kwargs)
        return HttpResponse(simplejson.dumps(data), mimetype='application/json')
    return wrapper


def not_allowed(request):
    return HttpResponseRedirect(reverse("not-allowed"))


def safe_string(text, result=""):
    try:
        return str(text)
    except (ValueError, AttributeError):
        return result


def trunc_string(text, length, ellipsis="..."):
    try:
        if len(text) < length:
            return text
        else:
            return "%s%s" % (text[:length-len(ellipsis)], ellipsis)
    except TypeError:
        return ""


def has_private_key(view_func):
    """Will check that the person accessing the page is doing
    so with the private URL """
    def wrapper(*args, **kwargs):
        request = args[0]
        if settings.ARECIBO_PRIVATE_ACCOUNT_NUMBER not in request.get_full_path().split("/"):
            return HttpResponseRedirect(settings.LOGIN_URL)
        return view_func(*args, **kwargs)
    return wraps(view_func)(wrapper)


def break_url(url):
    result = {"raw": url}
    parsed = list(urlparse(url))
    result["protocol"] = parsed[0]
    result["domain"] = parsed[1]
    result["query"] = urlunparse(["",""] + parsed[2:])
    return result


def redirect(name):
    return HttpResponseRedirect(reverse(name))


def memoize(prefix, time=60):
    """
    A simple memoize that caches into memcache, using a simple
    key based on stringing args and kwargs. Keep args simple.
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            key = hashlib.md5()
            for arg in itertools.chain(args, kwargs):
                key.update(str(arg))
            key = 'memoize:%s:%s' % (prefix, key.hexdigest())
            data = cache.get(key)
            if data is not None:
                return data
            data = func(*args, **kwargs)
            cache.set(key, data, time)
            return data
        return wrapper
    return decorator
