# coding: utf-8

import hashlib
import hmac
from builtins import bytes

import requests


class OTCBTCAPIBase(object):

    API_ENDPOINT = 'https://bb.otcbtc.com'

    def __init__(self, api_key='', api_secret=''):
        self.access_key = api_key
        self.api_secret = api_secret

    def build_url(self, uri):
        return self.API_ENDPOINT + uri

    def build_payload(self, method, uri, params):
        # parameters concated with "&", MUST BE IN ALPHABETICAL ORDER by parameters
        params = '&'.join(['%s=%s' % (k, v) for k, v in sorted(list(params.items()), key=lambda t: t[0])])
        # payload is a string represents this request, combiled with HTTP method, request URI and request parameters
        return '|'.join([method, uri, params])

    def generate_signature(self, payload):
        # signature: can be generated by HMAC-SHA256(payload, your_api_secret).to_hex
        return hmac.new(bytes(self.api_secret, 'ascii'), bytes(payload, 'ascii'), hashlib.sha256).hexdigest()

    def get(self, uri, params=None, **kwargs):
        r = requests.get(self.build_url(uri), params=params, **kwargs)
        return r.json()

    def post(self, uri, params=None, **kwargs):
        r = requests.post(self.build_url(uri), params=params, **kwargs)
        return r.json()
