# -*- coding:utf-8 -*- 
'''
Created on 2018/06/01
@author: wt
'''
from fcoin.cons import *
import hmac
import hashlib
import pandas as pd
import requests
import time
import base64


class DataAPI():
    def __init__(self, key='', secret=''):
        self.http = HT%SERVER
        self.http_public = HTPBL%SERVER
        self.http_market = HTMRK%SERVER
        self.http_orders = HTORD%SERVER
        self.http_account = HTACT%SERVER
        self.key = key
        self.secret = secret
        
        
    def authorize(self, key='', secret=''):
        self.key = key
        self.secret = secret
        
    
    def signed_request(self, method, url, **params):
        param=''
        if params:
            sort_pay = params.items()
            sort_pay.sort()
            for k in sort_pay:
                param += '&' + str(k[0]) + '=' + str(k[1])
            param = param.lstrip('&')
        timestamp = str(int(time.time() * 1000))

        if method == GET:
            if param:
                url = url + '?' +param
            sig_str = method + url + timestamp
        elif method == POST:
            sig_str = method + url + timestamp + param

        signature = self.get_signed(sig_str)

        headers = {
            'FC-ACCESS-KEY': self.key,
            'FC-ACCESS-SIGNATURE': signature,
            'FC-ACCESS-TIMESTAMP': timestamp

        }

        try:
            r = requests.request(method, url, headers=headers, json=params)
            r.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print(err)
            print(r.text)
        if r.status_code == 200:
            return r.json()
    
    def public_request(self, method, url, **params):
        try:
            r = requests.request(method, url, params=params)
            r.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print(err)
        if r.status_code == 200:
            return r.json()

    def get_signed(self, sig_str):
        sig_str = base64.b64encode(sig_str)
        signature = base64.b64encode(hmac.new(self.secret, sig_str, digestmod=hashlib.sha1).digest())
        return signature


    def server_time(self):
        return self.public_request(GET, self.http_public + ST)['data']


    def currencies(self):
        return self.public_request(GET, self.http_public + CURRENCY)['data']


    def symbols(self):
        js = self.public_request(GET, self.http_public + SYMBOLS)['data']
        df = pd.DataFrame(js)
        return df


    def get_ticker(self, symbol):
        return self.public_request(GET, self.http_market + TICKER%symbol)
    
    
    def get_kdata(self, freq='M1', symbol=''):
        js = self.public_request(GET, self.http_market + KDATA%(freq, symbol))
        df = pd.DataFrame(js['data'])
        df['id'] = df['id'].map(lambda x: int2time(x))
        df = df[KDATA_COLUMNS]
        df.columns = KDATA_REAL_COL
        return df
    
    
    def get_balance(self):
        """get user balance"""
        return self.signed_request(GET, self.http_account + 'balance')


    def list_orders(self, **payload):
        """get orders"""
        return self.signed_request(GET,'orders', **payload)


    def create_order(self, **payload):
        """create order"""
        return self.signed_request(POST,'orders', **payload)


    def buy(self,symbol, price, amount):
        """buy someting"""
        return self.create_order(symbol=symbol, side='buy', type='limit', price=str(price), amount=amount)


    def sell(self, symbol, price, amount):
        """sell someting"""
        return self.create_order(symbol=symbol, side='sell', type='limit', price=str(price), amount=amount)


    def get_order(self,order_id):
        """get specfic order"""
        return self.signed_request(GET, self.http_orders + order_id)


    def cancel_order(self,order_id):
        """cancel specfic order"""
        return self.signed_request(POST, self.http_orders + '%s/submit-cancel'%order_id)

    def order_result(self, order_id):
        """check order result"""
        return self.signed_request(GET, self.http_orders + '%s/match-results'%order_id)
    
    def get_depth(self, level, symbol):
        """get market depth"""
        return self.public_request(GET, self.http_market + 'depth/%s/%s'%(level, symbol))

    def get_trades(self,symbol):
        """get detail trade"""
        return self.public_request(GET, self.http_market + 'trades/%s'%symbol)

    
    
def int2time(timestamp):
        timestamp = int(timestamp)
        value = time.localtime(timestamp)
        dt = time.strftime('%Y-%m-%d %H:%M:%S', value)
        return dt


if __name__ == '__main__':
    api = DataAPI()
    print(api.get_kdata(freq='M1', symbol='btcusdt'))