#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys,httplib,urllib2
import json
from Queue import Queue  
import threading  
import time  

class _httpNewThread(threading.Thread):  
    def __init__(self, t_name,datx):  
        threading.Thread.__init__(self, name=t_name) 
        self.dat = datx
    def _private_request(self,get_data):
        print get_data
        response = urllib2.urlopen(get_data)
        try:
            resp_dict = json.loads(response.read())
            return resp_dict
        except Exception,ex:
            print ex
            return None
    def run(self):
            backstr = self._private_request(self.dat.askstr)
            self.dat.func(self.dat.callType,backstr)

class _callBackObj():
    def __init__(self,cmdType,askStr,BackFunc):
        self.askstr = askStr
        self.func = BackFunc
        self.callType = cmdType

class httprequest():
    def __init__(self,backFunc):
        self.baseHttps = 'https://www.okcoin.com/'
        self.callBackFunc = backFunc
        self.callTypes = ['kline']
    def _get_tonce(self):
        return int(time.time()*1000000)
    #使用https请求获取okcoin期货k线数据,默认10条数据,返回函数将由子线程返回结果
    def requestKline(self,contractType = 'quarter',symbol = 'btc_usd',ptype = '1min',size = 10,timestamp = ''):
        requeststr = ''
        if timestamp == '':
            requeststr = self.baseHttps + 'api/v1/future_kline.do?symbol=' + symbol + '&type=' + ptype + '&contract_type=' + contractType + '&size=' + str(size)
        else:
            requeststr = self.baseHttps + 'api/v1/future_kline.do?symbol=' + symbol + '&type=' + ptype + '&contract_type=' + contractType + '&size=' + str(size) + '&since=' + str(timestamp)
        self.requestWithStr('kline',requeststr,self.callBackFunc)
    def requestWithStr(self,callType,cmdStr,callFunc = None):
        if callFunc == None:
            callobj = _callBackObj(callType,cmdStr,self.callBackFunc)
            threadtmp = _httpNewThread(callType, callobj) 
            threadtmp.setDaemon(True)
            threadtmp.start()
        else:
            callobj = _callBackObj(callType,cmdStr,callFunc)
            threadtmp = _httpNewThread(callType, callobj) 
            threadtmp.setDaemon(True)
            threadtmp.start()
        