#
#    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/>.
#

from .script import Script
from ..utils.errors import ScriptError

class Ndx(Script):
    def __init__(self, *groups):
        super().__init__()
        for group in groups:
            setattr(self, group, [])
        self._col_len = 15
        self._space_len = 6

    def __get_indx(self, group):
        indx = getattr(self, group)

        if not isinstance(indx, list):
            raise ScriptError(indx)

        return indx

    def __str_one_group(self, group):
        indices = self.__get_indx(group)
        max_len = len(str(max(indices))) + 1
        spaces = self._space_len if max_len <= self._space_len else max_len
        ndx_group = '[ '+group+' ]'
        for i, idx in enumerate(indices):
            if i%self._col_len == 0:
                ndx_group += '\n'
            ndx_group += "{:{}}".format(idx, spaces)
        ndx_group += '\n'
        return ndx_group

    def __str__(self):
        ndx = '; Generated by MiMiCPy\n'
        for parameter in self.parameters:
            ndx += self.__str_one_group(parameter) + '\n\n'
        return ndx

    def rename_group(self, old_group, new_group): # does not maintain order
        self.__orddict__[new_group] = self.__orddict__.pop(old_group)

    @classmethod
    def from_string(cls, string):
        pass
