from drugtools.historical_nct_downloader import make_request, get_highest_version_number, step_generator 

#this uses the history downloader script to test downloads


def trial_downloads(nct_id):
    """
    Mirrors `download_and_handle_errors` and , without writing to a database
    Instead it writes to files
    """
    print("downloading {}".format(nct_id))
    r = make_request(nct_id,1,2)
    responses = [ r ]
    print(r.url)

    v = get_highest_version_number(r)

    if v == 2:
        pass
    elif v%2 == 0:
        for version_a, version_b in step_generator(v):
            print("\t versions {} & {}".format(version_a,version_b))
            req = make_request(nct_id,version_a,version_b)
            responses.append(req)
    elif v %2 == 1:
        for version_a, version_b in step_generator(v):
            print("\t downloading versions {} & {}".format(version_a,version_b))
            req = make_request(nct_id,version_a,version_b)
            responses.append(req)
        responses.append(make_request(nct_id,1,v))

    print("\tDownloaded {} versions".format(v))

    return responses


if __name__ == "__main__":
    test_list = ['NCT01303796', 'NCT01371708', 'NCT01374906', 'NCT01382602', 'NCT01384539', 'NCT01391546', 'NCT01392469', 'NCT01413178', 'NCT01416441', 'NCT01418339']

    for t in test_list:
        resp = trial_downloads(t)

