import pprint

import requests


def test_link(conn, user):
    print("Get update management dates")
    url = conn + '/management_dates'
    resp = requests.get(url)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    pprint.pprint(res)
    print('\n')

    name_id = user['name_id']
    url = conn + '/link?NameID=%s' % name_id
    payload = {
        'IDDUI': user['dui'],
        'NOM': user['last_name'],
        'PRENOM': user['first_name'],
        'NAISSANCE': user['dob'],
    }
    print("Creating link with the following payload:")
    pprint.pprint(payload)
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    pprint.pprint(res)
    print('\n')

    print("GET family info")
    url = conn + '/family_info?NameID=%s' % name_id
    resp = requests.get(url)
    resp.raise_for_status()
    data = resp.json()
    assert res['err'] == 0
    pprint.pprint(data)
    print('\n')

    # take family info and transform them into updatable data
    payload = data['data']
    # complete required fields
    payload['N0TELEDOSSIER'] = '42'
    payload['DROITALIMAGE'] = 'NON'
    payload['REVENUS']['CHOIXREVENU'] = ''
    # remove non editable fields
    for key in [
        'SITUATIONFAMILIALE',
        'SITUATIONFAMILIALE_label',
        'NBENFANTACTIF',
        'NBRLACTIF',
        'IDDUI',
        'CODEMISEAJOUR',
        'management_dates',
        'annee_reference',
        'annee_reference_label',
        'annee_reference_short',
    ]:
        payload.pop(key)
    for key in [
        'IDPERSONNE',
        'NOM',
        'PRENOM',
        'NOMJEUNEFILLE',
        'DATENAISSANCE',
        'CIVILITE',
        'INDICATEURRL',
        'CSP_label',
    ]:
        if 'RL1' in payload:
            payload['RL1'].pop(key)
        if 'RL2' in payload:
            payload['RL2'].pop(key)
    for key in [
        'MONTANTTOTAL',
        'DATEVALIDITE',
        'SFI',
        'IREVENUS',
        'RNF',
        'NBENFANTSACHARGE',
        'TYPEREGIME_label',
    ]:
        payload['REVENUS'].pop(key, None)
    for enfant in payload['ENFANT']:
        for key in [
            'id',
            'text',
            'NOM',
            'DATENAISSANCE',
            'SEXE',
            'PRENOMPERE',
            'PRENOMMERE',
            'NOMPERE',
            'NOMMERE',
            'RATTACHEAUTREDUI',
            'PRENOM',
            'clae_cantine_current',
        ]:
            enfant.pop(key)
        enfant['AUTORISATIONURGENCEMEDICALE'] = 'OUI'
        # manage contact fields
        for contact in enfant.get('CONTACT', []):
            contact.pop('id')
            contact.pop('text')
            contact.pop('LIENPARENTE_label')
        if 'SANITAIRE' not in enfant:
            continue
        # manage handicap data (not the same schema)
        handicap_fields = [
            'AUTREDIFFICULTE',
            'ECOLESPECIALISEE',
            'INDICATEURAUXILIAIREVS',
            'INDICATEURECOLE',
            'INDICATEURHANDICAP',
            'INDICATEURNOTIFMDPH',
        ]
        enfant['SANITAIRE']['HANDICAP'] = {}
        for key in handicap_fields:
            enfant['SANITAIRE']['HANDICAP'][key] = enfant['SANITAIRE'].pop(key)
        # manage allergie data (not the same schema)
        if 'ALLERGIE' not in enfant['SANITAIRE']:
            continue
        new_allergie = {
            'ASTHME': False,
            'MEDICAMENTEUSES': False,
            'ALIMENTAIRES': False,
            'AUTRES': None,
        }
        for allergie in enfant['SANITAIRE']['ALLERGIE']:
            if allergie['TYPE'] == 'AUTRES':
                if allergie['ALLERGIQUE'] == 'OUI':
                    new_allergie['AUTRES'] = allergie['NOMALLERGIE']
                continue
            new_allergie[allergie['TYPE']] = allergie['ALLERGIQUE']
        enfant['SANITAIRE']['ALLERGIE'] = new_allergie
    # add partial update flags
    flags = [
        'maj:adresse',
        'maj:rl1',
        'maj:rl1_adresse_employeur',
        'maj:rl2',
        'maj:rl2_adresse_employeur',
        'maj:revenus',
    ]
    for i in range(0, 6):
        flags += [
            'maj:enfant_%s' % i,
            'maj:enfant_%s_sanitaire' % i,
            'maj:enfant_%s_sanitaire_medecin' % i,
            'maj:enfant_%s_sanitaire_vaccin' % i,
            'maj:enfant_%s_sanitaire_allergie' % i,
            'maj:enfant_%s_sanitaire_handicap' % i,
            'maj:enfant_%s_assurance' % i,
            'maj:enfant_%s_contact' % i,
        ]
    for key in flags:
        payload[key] = True

    print("Update family info with the following payload:")
    pprint.pprint(payload)
    url = conn + '/update_family_info?NameID=%s' % name_id
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    pprint.pprint(res)
    print('\n')

    print("GET children info")
    url = conn + '/children_info?NameID=%s' % (name_id)
    resp = requests.get(url)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    pprint.pprint(res)
    print('\n')

    for child in data['data']['ENFANT']:
        print("GET child info")
        url = conn + '/child_info?NameID=%s&idpersonne=%s' % (name_id, child['IDPERSONNE'])
        resp = requests.get(url)
        resp.raise_for_status()
        res = resp.json()
        assert res['err'] == 0
        pprint.pprint(res)
        print('\n')

        print("GET child contact info")
        url = conn + '/child_contacts_info?NameID=%s&idpersonne=%s' % (name_id, child['IDPERSONNE'])
        resp = requests.get(url)
        resp.raise_for_status()
        res = resp.json()
        assert res['err'] == 0
        pprint.pprint(res)
        print('\n')

    print("Deleting link")
    url = conn + '/unlink?NameID=%s' % name_id
    resp = requests.post(url)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    pprint.pprint(res)
    print('\n')
