import ovation.lab.constants as constants
import ovation.lab.results as results
import ovation.download as dowload

from ovation.lab.session import connect

"""
Explanation: Download sample result files
Setup
End of explanation
"""


s = connect(input("Email: "), api=constants.LAB_STAGING_HOST) # use constants.LAB_PRODUCTION_HOST for production

"""
Explanation: API Key
Create an API key in the Ovation application at Account > Settings > API Keys (https://support.ovation.io/article/52-api-overview)
Connection
End of explanation
"""


batch = input("Batch (workflow ID): ")

"""
Explanation: Find fastq results for samples in batch
End of explanation
"""


fastq_results = results.get_sample_results(s, result_type='fastq', workflow_id=2418)

"""
Explanation: results.get_sample_results pulls all WorkflowSampleResults for the given batch and result type. In the workflow, Ovation associated each file with its corresponding sample, and created a WorkflowSampleResult that referenced the uploaded file.
End of explanation
"""


urls = results.get_file_urls(s, fastq_results)

"""
Explanation: results.get_file_urls retrieves temporary, pre-signed download URLs for each file Resource described by the WorkflowSampleResults.
End of explanation
"""


download.download_urls([d['url'] for d in urls])

"""
Explanation: urls is a list of dictionaries that have a "url" attribute and an "etag" attribute. You can use the pre-signed "url" to read/download the file. The etag is like a "version" of the file. If the file has changed, the etag will change too.
Using download.download_urls, you can download all of the files to the local file system. download_urls runs downloads in parallel.
End of explanation
"""


