import base64
import datetime
import hashlib
import hmac
import random
from urllib import parse as urlparse

from django.utils.encoding import smart_bytes
from django.utils.http import quote, urlencode

# Simple signature scheme for query strings
# from http://git.entrouvert.org/hobo.git/tree/hobo/signature.py


def sign_url(url, key, algo='sha256', timestamp=None, nonce=None):
    parsed = urlparse.urlparse(url)
    new_query = sign_query(parsed.query, key, algo, timestamp, nonce)
    return urlparse.urlunparse(parsed[:4] + (new_query,) + parsed[5:])


def sign_query(query, key, algo='sha256', timestamp=None, nonce=None):
    if timestamp is None:
        timestamp = datetime.datetime.utcnow()
    timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
    if nonce is None:
        nonce = hex(random.getrandbits(128))[2:]
    new_query = query
    if new_query:
        new_query += '&'
    new_query += urlencode((('algo', algo), ('timestamp', timestamp)))
    if nonce:  # we don't add nonce if it's an empty string
        new_query += '&nonce=' + quote(nonce)
    signature = base64.b64encode(sign_string(new_query, key, algo=algo))
    new_query += '&signature=' + quote(signature)
    return new_query


def sign_string(s, key, algo='sha256'):
    digestmod = getattr(hashlib, algo)
    if isinstance(key, str):
        key = key.encode('utf-8')
    hash = hmac.HMAC(smart_bytes(key), digestmod=digestmod, msg=smart_bytes(s))
    return hash.digest()


def check_url(url, key, known_nonce=None, timedelta=30):
    parsed = urlparse.urlparse(url, 'https')
    return check_query(parsed.query, key, known_nonce=known_nonce, timedelta=timedelta)


def check_query(query, key, known_nonce=None, timedelta=30):
    parsed = urlparse.parse_qs(query)
    if not ('signature' in parsed and 'algo' in parsed and 'timestamp' in parsed):
        return False
    if known_nonce is not None:
        if ('nonce' not in parsed) or known_nonce(parsed['nonce'][0]):
            return False
    unsigned_query, signature_content = query.split('&signature=', 1)
    if '&' in signature_content:
        return False  # signature must be the last parameter
    signature = base64.b64decode(parsed['signature'][0])
    algo = parsed['algo'][0]
    timestamp = parsed['timestamp'][0]
    timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')
    if abs(datetime.datetime.utcnow() - timestamp) > datetime.timedelta(seconds=timedelta):
        return False
    return check_string(unsigned_query, signature, key, algo=algo)


def check_string(s, signature, key, algo='sha256'):
    # constant time compare
    signature2 = sign_string(s, key, algo=algo)
    if len(signature2) != len(signature):
        return False
    res = 0
    for a, b in zip(signature, signature2):
        res |= a ^ b
    return res == 0
