import json
import sys

output_filename = sys.argv[1]

print('output to', output_filename)

thematique_slug = '13ave-thematiques'
dispositif_slug = '13ave-dispositifs'
reponse_type_slug = '13ave-dga-p-reponses-types'

from wcs.carddef import CardDef

data = {}

Thematique = CardDef.get_by_urlname(thematique_slug).data_class()
Dispositif = CardDef.get_by_urlname(dispositif_slug).data_class()
ReponseType = CardDef.get_by_urlname(reponse_type_slug).data_class()

data['thematique'] = [{
    'digest': thematique.digest,
    'name': thematique.data[thematique.formdef.fields[0].id]
} for thematique in Thematique.select()]
dispositifs = Dispositif.select()
for dispositif in dispositifs:
    # reconstruct 2_display
    field_id = str(dispositif.formdef.fields[1].id)
    dispositif.data[field_id + '_display'] = dispositif.formdef.fields[1].store_display_value(dispositif.data, field_id)
    dispositif.set_auto_fields()

data['dispositif'] = [{
    'digest': dispositif.digest,
    'name': dispositif.data[dispositif.formdef.fields[0].id],
    'thematique': dispositif.data[dispositif.formdef.fields[1].id + '_display'],
    } for dispositif in dispositifs]

data['reponse_type'] = []

for reponse_type in ReponseType.select():
    # reconstruct 2_display
    field_id = str(reponse_type.formdef.fields[1].id)
    reponse_type.data[field_id + '_display'] = reponse_type.formdef.fields[1].store_display_value(reponse_type.data, field_id)
    data['reponse_type'].append({
        'digest': reponse_type.digest + str(reponse_type.data[reponse_type.formdef.fields[1].id + '_display']),
        'title': reponse_type.data[reponse_type.formdef.fields[0].id],
        'dispositif': reponse_type.data[reponse_type.formdef.fields[1].id + '_display'],
        'message': reponse_type.data[reponse_type.formdef.fields[2].id],
    })

with open(output_filename, 'w') as fd:
    json.dump(data, fd, indent=2)
