#!/usr/bin/env python
"""Converts a readdy trajectory to a set of LAMMPS configuration
files"""
from pathlib import Path

from hydrogels import trajectory
from hydrogels.trajectory.core import ParticleTrajectory, TopologyTrajectory

from softnanotools.logger import Logger
logger = Logger('CONVERT')

def main(h5: str, folder: str = None, skip_topology: bool = False, **kwargs):
    logger.info('Running convert...')
    name = h5.replace('.h5', '')
    logger.info(f'Declared name as {name}')

    # create folder and ensure output files go there


    # insert code here
    trajectory = ParticleTrajectory(h5)
    logger.info('Successfully read trajectory')
    if skip_topology:
        target = f'dump.{name}'
        if folder:
            folder = Path(folder)
            folder.mkdir(exist_ok=True)
            target = Path(folder) / target
        topology = TopologyTrajectory(h5)
        trajectory.to_LAMMPS_dump(target)

    else:
        target = f'lammps.{name}.conf'
        if folder:
            folder = Path(folder)
            for f in folder.glob('*'):
                f.unlink()
            folder.mkdir(exist_ok=True)
            target = Path(folder) / target
        topology = TopologyTrajectory(h5)
        trajectory.to_LAMMPS_configuration(target, topology)

    logger.info('Done!')
    return

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='convert.py - auto-generated by softnanotools')
    parser.add_argument('h5')
    parser.add_argument('--folder')
    parser.add_argument('--skip-topology', action='store_true')
    main(**vars(parser.parse_args()))
