#  Copyright (C) 2021 The authors of Py-ChemShell
#
#  This file is part of Py-ChemShell.
#
#  Py-ChemShell is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation, either version 3 of the
#  License, or (at your option) any later version.
#
#  Py-ChemShell is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with Py-ChemShell.  If not, see
#  <http://www.gnu.org/licenses/>.

__author__ = 'You Lu <you.lu@stfc.ac.uk>'

from ...io import format

# AMBER coordinate/restart file
# see: https://ambermd.org/FileFormats.php#restart
def parse(filename, _regex=None, receiver=None, prefix='', **kwargs):
    '''Parse an AMBER coordinate/restart (rst) file'''

    from numpy   import float64, genfromtxt
    from os      import path
    from ...data import unitconvert

    delimiters = []
    dtype      = None
    entry      = ''
    row        = 0
    tbuff      = []

    if not receiver:
        print("\n>>> ERROR: in function amber_rst.parse() a valid receiver must be given!")
        exit(999)

    # YL 13/08/2022: path prefix
    filename = path.join(prefix, filename)

    with open(filename, 'r') as fp:
        lines = fp.readlines()[:2]
        receiver.title = '_'.join(lines[0].strip().split())
        receiver.natoms = lines[1].split()[0]

    abuff = genfromtxt(filename,
                       skip_header=2,
                       dtype=float64,
                      )

    # override the coordinates
    receiver.coords = abuff.ravel()[:receiver.natoms*3]*unitconvert.unit2au['angstrom']

    # YL 24/06/2021: not in use now but will be needed in future
    #                and we will consider then if a.u. for time should be used internally (1 a.u. = 2.18769126364*10**6 m/s)
    # velocity unit in AMBER RST: Angstroms per 1/20.455 ps
    # converted to Bohr/ps
    velocities = abuff.ravel()[receiver.natoms*3:receiver.natoms*6]*unitconvert.unit2au['angstrom']/20.455



