#  Copyright (C) 2022 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 sys import stdout

def _patchNucleotides(_bioFrag, _ffObj, _seg, _segFrag, _residue_patches, mute=True):
    '''Patch nucleotides'''

    from numpy      import unique
    from ...dl_py2f import utils

    resIDs = unique(_segFrag.resIDs)
    strbuff = ''

    # loop over all residues
    for i, resID in enumerate(resIDs):
        residues = _segFrag.residues[_segFrag.resIDs==resID]
        if unique(residues).size > 1:
            print(f'\n WARNING: segment {_seg} residue ID {resID} contains multiple residue names!')
        residue = residues[0].decode().strip()
        patch = utils.dictutils.getValue(_ffObj.nucleotide_patches, residue, case_sensitive=False, raiseError=False)
        if patch:
            strbuff += 'patch {} {}:{}\n'.format(patch, _seg, resID)
            _residue_patches.update({residue:patch})
            # the original title is very long
            _bioFrag.title = 'polynucleotide'

    # do again for terminal bases
    for i, resID in enumerate(resIDs):
        residues = _segFrag.residues[_segFrag.resIDs==resID]
        if unique(residues).size > 1:
            print(f'\n WARNING: segment {_seg} residue ID {resID} contains multiple residue names!')
        residue = residues[0].decode().strip()
        patch = utils.dictutils.getValue(_ffObj.nucleotide_patches_terminal, residue, case_sensitive=False, raiseError=False)
        if patch:
            strbuff += 'patch {} {}:{}\n'.format(patch, _seg, resID)
            _residue_patches.update({residue:patch})
            # the original title is very long
            _bioFrag.title = 'polynucleotide'

    return strbuff


