import datetime
import pprint

import requests


def test_link(conn, user):
    name_id = user['name_id']
    url = conn + '/link?NameID=%s' % name_id
    payload = {
        'IDENTFAMILLE': user['family'],
        'NOM': user['last_name'],
        'PRENOM': user['first_name'],
    }
    print("Creating link with the following payload:")
    pprint.pprint(payload)
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    pprint.pprint(res)
    assert res['err'] == 0
    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()
    pprint.pprint(data)
    assert data['err'] == 0
    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()
    pprint.pprint(res)
    assert res['err'] == 0
    print('\n')

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

        print("and GET school info")
        url = conn + '/child_schooling_info?NameID=%s&idpersonne=%s&schooling_date=%s' % (
            name_id,
            child['IDENT'],
            datetime.date.today().strftime('%Y-%m-%d'),
        )
        resp = requests.get(url)
        resp.raise_for_status()
        res = resp.json()
        pprint.pprint(res)
        assert res['err'] == 0
        print('\n')

        print("and GET activities info")
        url = conn + '/child_activities_info?NameID=%s&idpersonne=%s&schooling_date=%s' % (
            name_id,
            child['IDENT'],
            datetime.date.today().strftime('%Y-%m-%d'),
        )
        resp = requests.get(url)
        resp.raise_for_status()
        res = resp.json()
        pprint.pprint(res)
        assert res['err'] == 0
        print('\n')

    print("GET school list")
    url = conn + '/school_list'
    payload = {
        'num': data['data']['RESPONSABLE1']['ADRESSE']['NORUE'],
        'street': data['data']['RESPONSABLE1']['ADRESSE']['ADRESSE1'],
        'zipcode': data['data']['RESPONSABLE1']['ADRESSE']['CODEPOSTAL'],
        'city': data['data']['RESPONSABLE1']['ADRESSE']['VILLE'],
        'schooling_date': datetime.date.today().strftime('%Y-%m-%d'),
    }
    resp = requests.get(url, params=payload)
    resp.raise_for_status()
    res = resp.json()
    pprint.pprint(res)
    assert res['err'] == 0
    print('\n')
    return

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