#
#    MiMiCPy: Python Based Tools for MiMiC
#    Copyright (C) 2020-2021 Bharath Raghavan,
#                            Florian Schackert
#
#    This file is part of MiMiCPy.
#
#    MiMiCPy 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.
#
#    MiMiCPy 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 this program. If not, see <http://www.gnu.org/licenses/>.
#

"""Module for GROMACS mdp files"""

from .script import Script
from ..utils.errors import ParserError


class Mdp(Script):
    """formats GROMACS mdp files"""

    def __init__(self, **kwargs):
        super().__init__()
        if 'title' not in kwargs:
            kwargs['title'] = 'MiMiC run'
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        mdp = '; GROMACS parameters for {} generated by MiMiCPy\n'.format(self.title)
        for parameter in self.parameters:
            attribute = getattr(self, parameter)
            if attribute is None or parameter == 'title':
                continue
            parameter = parameter.replace('_', '-')
            mdp += '{} = {}\n'.format(parameter, attribute)
        return mdp

    @classmethod
    def from_string(cls, string):
        kwargs = {}
        for i, line in enumerate(string.splitlines()):
            line = line.strip()
            if line.startswith(';') or line == '':
                continue
            assignment = line.split(';')[0].split('=')
            if len(assignment) != 2:
                raise ParserError(file_type='mdp', line_number=i)
            parameter, attribute = assignment
            kwargs.update({parameter.strip(): attribute.strip()})
        return cls(**kwargs)
