from dstruct import DataStructFromJSON, DataField, datafield

# taken from the basic example
class AccountSummaryFromFile(DataStructFromJSON):
    
    user = DataField()
    type = DataField('account', 'account-type')
    ballance = DataField('account', 'account-ballance')
    # you can pass functions under the keyword "parser" to parse raw data parsing
    account_number = DataField('account', 'account-number', parser=lambda s: 'X'*len(s[:-4])+s[-4:])

AccountSummaryFromFile('data_files/bank_data.json')

"""
Explanation: advanced dstruct usage

1. we repeate a part of the basic example to make an account summary
End of explanation
"""


from dstruct import DataStruct
from datetime import datetime

class Transaction(DataStruct):
    
    amount = DataField()

    @datafield(path=None)
    def time(self, data):
        s = data['utc-unix']
        tz = data['time-zone']
        if 'UTC' not in tz:
            raise ValueError("Unknow time-zone standard: '%s'" % tz)
        else:
            dif = tz.replace('UTC', '')
            # trick for adding time-zone
            s = eval(str(s)+dif+'*60*60')

        dt = datetime.fromtimestamp(s)
        # return the parsed epoch time
        # for the given time-zone
        return dt.strftime('%Y-%m-%d %H:%M:%S')
    
    @datafield('source')
    def source(self, data):
        t = data['type']
        # we use the transaction type
        # to identify which kind of
        # `DataStruct` should be used
        if '-' in t:
            s = ''
            for sub in t.split('-'):
                s += sub.capitalize()
        else:
            s = t.capitalize()
        
        # we use `eval` to grab
        # the appropriate struct
        cls = eval(s)
        return cls(data)
    

class TransactionSource(DataStruct):
    
    ref = DataField()
    
class Purchase(TransactionSource):

    type = DataField()
    at = DataField('name')
    card = DataField(parser=lambda s: 'X'*len(s[:-4])+s[-4:])
    
class MobileDeposit(TransactionSource):

    type = DataField()
    note = DataField()
    check_number = DataField('check-number')


class DetailedAccountSummary(AccountSummaryFromFile):
    
    last_withdraw = DataField('account', 'withdrawn', '0', parser=Transaction)
    last_deposit = DataField('account', 'deposited', '0', parser=Transaction)

"""
Explanation: 2. use nested DataStructs

nesting DataStructs allows for much more complex parsing patterns.
End of explanation
"""


print(DetailedAccountSummary('data_files/bank_data.json'))

"""
Explanation: The Parsed Account Summary
End of explanation
"""


