import collections
import csv
import pathlib
import textwrap

import exifread

sample_to_snippets = collections.OrderedDict()

# Read samples.tsv
samples_directory = pathlib.Path('samples')
sample_to_attributes = collections.OrderedDict()
with samples_directory.joinpath('samples.tsv').open() as read_file:
    reader = csv.DictReader(read_file, delimiter='\t')
    for row in reader:
        sample_id = row['sample_id']
        markdown_list = '\n'.join(f'+ {k}: {v}' for k, v in row.items())
        markdown_list = f'\n## Sample information:\n\n{markdown_list}\n'
        sample_to_snippets[sample_id] = [markdown_list]

# Collect paths for sample images
image_paths = list()
image_paths.extend(samples_directory.glob('sample-sites/*.jpg'))
image_paths.extend(samples_directory.glob('plates/*.jpg'))

# Generate markdown snippets for each image
for path in image_paths:
    sample_id, _ = path.stem.split('-', 1)
    with path.open('rb') as read_file:
        tags = exifread.process_file(read_file, details=False)
    gps_coords = exifread.utils.get_gps_coords(tags)
    snippet = textwrap.dedent(f'''\

    ## {path.stem}

    + EXIF DateTimeOriginal: {tags.get('EXIF DateTimeOriginal')}
    + Geolocation: {gps_coords}

    ![{path.stem}]({path.relative_to(samples_directory)})
    ''')
    sample_to_snippets[sample_id].append(snippet)

# Generate markdown documents with details for each sample
for sample_id, snippets in sample_to_snippets.items():
    markdown = textwrap.dedent(f'''\
    # Autogenerated details for `{sample_id}`
    ''')
    markdown += ''.join(snippets)
    path = samples_directory.joinpath(f'{sample_id}-details.md')
    path.write_text(markdown)
