"""
Turns an ISO639-9 tab file as downloadable from
https://iso639-3.sil.org/code_tables/download_tables into a JSON string, which
is embedded in a python source file.

You can update the database by pointing to an updated CSV_STORE file when
running this script.
"""
import os
import json
import csv

PICKLED_STORE = "iso639_3_20220311.py"
CSV_STORE = "iso-639-3-20220311.tab"
FIELDNAMES = ['alpha_3', 'Part2B', 'Part2T', 'alpha_2', 'Scope', 'Language_Type', 'name', 'Comment']

if __name__ == "__main__":
    this_dir, this_filename = os.path.split(__file__)  # Get path
    csv_store_path = os.path.join(this_dir, CSV_STORE)
    pickled_store_path = os.path.join(this_dir, PICKLED_STORE)
    with open(csv_store_path) as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024))
        csvfile.seek(0)
        languages_raw = [l for l in csv.DictReader(csvfile, fieldnames=FIELDNAMES, dialect=dialect)]
        languages_raw.pop(0) #discard header

    with open(pickled_store_path, 'w') as pickle_file:
        pickle_file.write(f"LANGUAGES=\"\"\"{json.dumps(languages_raw)}\"\"\"")