# coding=utf-8
import hashlib
import hmac
import time
import requests

_base_url = 'https://bittrex.com/api/v1.1'
_headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'User-Agent': 'python-requests',
        'Accept-charset': 'utf-8',
}
_requests = {
    'post': requests.post,
    'get': requests.get,
}
_milliseconds = 1000


def _nonce():
    return str(int(time.time() * _milliseconds))


def _sign(private_key, message):
    for arg in [private_key, message]:
        if not isinstance(arg, bytes):
            raise TypeError(type(arg), arg)
    signature = hmac.new(key=private_key, msg=message, digestmod=hashlib.sha512)
    hexsignature = signature.hexdigest()
    return hexsignature


def _request(method, path, public_key, private_key, data=None, params=None):
    session = requests.Session()

    url = ''.join([_base_url, path])
    headers = _headers.copy()

    nonce = _nonce()
    if 'public' not in url:
        params['apikey'] = public_key
        params['nonce'] = nonce

    r = requests.Request(method, url=url, data=data, params=params)
    req_url = r.url
    headers['apisign'] = _sign(private_key=private_key.encode(), message=req_url.encode())

    r = requests.Request(method, url=url, headers=headers, data=data, params=params)
    r = r.prepare()
    response = session.send(r)

    try:
        ret = response.json()
    except Exception as e:
        print('{0}: {1}'.format(e.__class__.__name__, e))
        return response.text
    if isinstance(ret, dict) and not ret.get('success', False):
        return ret.get('message', ret)
    return ret


def get(public_key, private_key, path, params=None):
    return _request('get', path, public_key, private_key, params=params)


def post(public_key, private_key, path, data):
    return _request('post', path, public_key, private_key, data)
