"""
eosls executable script to list available datafiles in current folder with some metadata information.

Author: Jochen Stahn (algorithms, python draft),
        Artur Glavic (structuring and optimisation of code)
"""
import os
import logging

from eos.command_line import commandLineArgs

def main():
    logging.getLogger().setLevel(logging.CRITICAL)
    clas = commandLineArgs([], 'eosls', extra_args=[
        dict(dest='path', nargs='*', default=['.'], help='paths to list file in')])

    from glob import glob
    import tabulate
    from eos.file_reader import AmorHeader

    files = []
    for path in clas.path:
        files+=glob(os.path.join(path, 'amor*.hdf'))
    files.sort()

    data = {
        'File name': [],
        'Start Time': [],
        'mu': [],
        'nu': [],
        'div': [],
        'Sample': [],
        'T [K]': [],
        'H [T]': [],
        }
    for fi in files:
        data['File name'].append(os.path.basename(fi))
        ah = AmorHeader(fi)
        data['Sample'].append(ah.sample.name)
        data['Start Time'].append(ah.fileDate.strftime('%y %m-%d %H:%M:%S'))
        data['mu'].append('%.3f' % ah.geometry.mu)
        data['nu'].append('%.3f' % ah.geometry.nu)
        data['div'].append('%.3f' % ah.geometry.div)

        T = ah.sample.sample_parameters.get('temperature', None)
        data['T [K]'].append(T.magnitude if T is not None else '-')

        H = ah.sample.sample_parameters.get('magnetic_field', None)
        data['H [T]'].append(H.magnitude if H is not None else '-')

    print(tabulate.tabulate(data, headers="keys"))

if __name__ == '__main__':
    main()
