from dstruct import DataStruct, DataField

raw_data = {
    "a": 1,
    "b": {
        "c": 2,
        "d": 3
    }
}

from dstruct import DataStruct, DataField

class A(DataStruct):
    
    a = DataField()
    c = DataField('b', 'c')
    d = DataField('b', 'd')

A(raw_data)

"""
Explanation: basic dstruct usage

1. sift through a data set for relevant information:
End of explanation
"""


from dstruct import DataStructFromJSON, DataField

class AccountSummaryFromJSON(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:])

AccountSummaryFromJSON('data_files/bank_data.json')

"""
Explanation: 2. import data sets from json files
End of explanation
"""


from dstruct import DataStructFromCSV, datafield

class AverageUserFromCSV(DataStructFromCSV):

    @datafield(path=None)
    def age(self, data):
        total = 0
        for name in data:
            total += int(data[name]['Age'])
        return round(float(total)/len(data), 1)
    
    @datafield(path=None)
    def weight(self, data):
        total = 0
        for name in data:
            total += int(data[name]['Weight'])
        return round(float(total)/len(data), 1)


AverageUserFromCSV('data_files/wide.csv')

"""
Explanation: 3. import data sets from csv files:

The datafield decorator, wraps complex parsers
End of explanation
"""


narrow = AverageUserFromCSV('data_files/narrow.csv')

"""
Explanation: + DataStructFromCSV understands wide and narrow form data representations
End of explanation
"""


wide = AverageUserFromCSV('data_files/wide.csv')

"""
Explanation: | Person | Variable | Value |
|--------|----------|-------|
| Bob    | Age      | 32    |
| Bob    | Weight   | 178   |
| Alice  | Age      | 24    |
| Alice  | Weight   | 150   |
| Steve  | Age      | 64    |
| Steve  | Weight   | 195   |
End of explanation
"""


narrow == wide

"""
Explanation: | Person | Age | Weigth |
|--------|-----|--------|
| Bob    | 32  | 178    |
| Alice  | 24  | 150    |
| Steve  | 64  | 195    |
End of explanation
"""


