# -*- coding: utf-8 -*-


import json
import logging
import threading
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.ext.ExecutionFilter import ExecutionFilter


class BaseHelper():
    @staticmethod
    def object2kvstring(o):
        return json.dumps(o.__dict__)
        
    @staticmethod
    def kvstring2object(kvstring, object):
        return BaseHelper.kv2object(json.loads(kvstring), object)


    @staticmethod
    def kv2object(kv, Object):   
        o = Object()
        map(lambda x: o.__setattr__(x, kv[x].encode('ascii') if type(kv[x]) == unicode else kv[x]), kv.keys())
        return o
        
        
class OrderHelper(BaseHelper):
    pass
     
#     @staticmethod
#     def object2kvstring(contract):
#         return json.dumps(contract.__dict__)
#  
#     @staticmethod
#     def kvstring2object(sm_order):
#         return OrderHelper.kv2object(json.loads(sm_order))
#  
#  
#     @staticmethod
#     def kv2object(m_order):   
#         newOrder = Order()
#         map(lambda x: newOrder.__setattr__(x, m_order[x].encode('ascii') if type(m_order[x]) == unicode else m_order[x]), m_order.keys())
#         return newOrder

    
class ExecutionFilterHelper(BaseHelper):
    pass

    


class ContractHelper(BaseHelper):
    
    def __init__(self, contractTuple):
        self.makeContract(contractTuple)
    
    
    @staticmethod
    def makeContract(contractTuple):
        newContract = Contract()
        newContract.m_symbol = contractTuple[0]
        newContract.m_secType = contractTuple[1]
        newContract.m_exchange = contractTuple[2]
        newContract.m_currency = contractTuple[3]
        newContract.m_expiry = contractTuple[4]
        newContract.m_strike = contractTuple[5]
        newContract.m_right = contractTuple[6]
        logging.debug( 'Contract Values:%s,%s,%s,%s,%s,%s,%s:' % contractTuple)
        return newContract
    
    @staticmethod
    def convert2Tuple(newContract):
        newContractTuple = (newContract.m_symbol,\
                            newContract.m_secType,\
                            newContract.m_exchange,\
                            newContract.m_currency,\
                            newContract.m_expiry,\
                            newContract.m_strike,\
                            newContract.m_right, newContract.m_conId)
        logging.debug( 'Contract Values:%s,%s,%s,%s,%s,%s,%s %s:' % newContractTuple)
        return newContractTuple
    

    @staticmethod
    def contract2kvstring(contract):
        return json.dumps(contract.__dict__)



    @staticmethod
    def kvstring2contract(sm_contract):
        
        return ContractHelper.kv2contract(json.loads(sm_contract))


    @staticmethod
    def kv2contract(m_contract):
        
        newContract = Contract()
        map(lambda x: newContract.__setattr__(x, m_contract[x].encode('ascii') if type(m_contract[x]) == unicode else m_contract[x]), m_contract.keys())
        return newContract
    


    
    @staticmethod
    def printContract(contract):
        s = '[%s-%s-%s-%s-%s-%s-%s-%s]' % (contract.m_symbol,
                                                       contract.m_secType,
                                                       contract.m_exchange,
                                                       contract.m_currency,
                                                       contract.m_expiry,
                                                       contract.m_strike,
                                                       contract.m_right,
                                                       contract.m_conId)
        #logging.info(s)
        return s
    
    @staticmethod
    def makeRedisKey(contract):
        #print "makerediskey %s" % ContractHelper.printContract(contract)
#20150904        
        contract.m_strike = int(contract.m_strike)
        #contract.m_strike = contract.m_strike
        
        if contract.m_secType == 'OPT':
            s = '%s-%s-%s-%s' % (contract.m_symbol,
                                                           contract.m_expiry,
                                                           contract.m_strike,
                                                           contract.m_right)
        else:
            s = '%s-%s-%s-%s' % (contract.m_symbol,
                                                           contract.m_expiry,
                                                           contract.m_secType, '')
            
        return s
      
    @staticmethod
    def makeRedisKeyEx(contract, old=False):
        # this routine is to circumvent a problem in makeRedisKey with 
        # the key in position 3 having different meanings under different conditions.
        #  
        # 
        # to differentiate the keys generated by the old and new functions, 
        # contract keys created using this routine have their last slot
        # hard coded a magic number 102
        
        if (old):
            return ContractHelper.makeRedisKey(contract)
        
        #contract.m_strike = int(contract.m_strike)
        #contract.m_strike = contract.m_strike
# amend 10/22 
# add exchange to the key         
#         s = '%s-%s-%s-%s-%s-%s-%s-%d' % (contract.m_symbol,
#                                                            contract.m_expiry,
#                                                            contract.m_strike,
#                                                            contract.m_right,
#                                                            contract.m_secType,
#                                                            contract.m_currency,
#                                                             
#                                                            contract.m_exchange,
#                                                             
#                                                            102)
        
# amend 12/1
#change strike format to 2 dp        
        s = '%s-%s-%.2f-%s-%s-%s-%s-%d' % (contract.m_symbol,
                                                           contract.m_expiry,
                                                           float(contract.m_strike),
                                                           contract.m_right,
                                                           contract.m_secType,
                                                           contract.m_currency,
                                                            
                                                           contract.m_exchange,
                                                            
                                                           102)
        
        return s
    
    
    @staticmethod
    def is_equal(c1, c2):
        return ContractHelper.makeRedisKeyEx(c1) == ContractHelper.makeRedisKeyEx(c2) 

    
# def str2dict(s):
#     return ast.literal_eval(s)

def dict2str(dict):
    # enclose strings in double quotes
    return '{'  + ', '.join('"%s" : %s' % (k, '"%s"' % v if type(v) == str else v) for k, v in dict.iteritems()) + '}'   
    


