from pathlib import Path
from datetime import datetime

import elabapi_python


API_HOST_URL = 'https://eln-geo.ca.hrz.tu-darmstadt.de/api/v2'
# replace with your api key, see https://doc.elabftw.net/api.html
API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# setup api configuration
configuration = elabapi_python.Configuration()
configuration.api_key['api_key'] = API_KEY
configuration.api_key_prefix['api_key'] = 'Authorization'
configuration.host = API_HOST_URL
configuration.debug = False
configuration.verify_ssl = True

# create an instance of the API class
api_client = elabapi_python.ApiClient(configuration)
# fix issue with Authorization header not being properly set by the generated lib
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)

# create an instance of the experiments API class
experimentsApi = elabapi_python.ExperimentsApi(api_client)

experiments = experimentsApi.read_experiments()
for experiment in experiments:
    name = f"{experiment.id} {experiment.title}"
    print(name)

# get .eln archive via API
# output .eln archive location
experiments = {experiment.id: experiment for experiment in experiments}
experiment = experiments[221]  # Tensile Test has ID 221
rocrate_archive_path = Path(datetime.now().strftime('%Y-%m-%d-%H%M%S-export.eln'))
with open(rocrate_archive_path, 'wb') as file:
    # the _preload_content flag is necessary so the api_client doesn't try and deserialize the response
    file.write(experimentsApi.get_experiment(experiment.id, format='eln', _preload_content=False).data)

elabid = experiment.elabid
