#  Copyright (C) 2018 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@stfc.ac.uk'
# Oct 2018
# Mar 2021 revised

import sys
from os  import path, sep
sys.path.append(path.join(path.dirname(__file__), 'src'))

__all__ = 'propka'


# the PROPKA main() function adapted for ChemShell
def run(filename):
    '''Reads in structure files, calculates pKa values, and prints pKa files'''

    from contextlib import redirect_stdout
    from propka     import lib, molecular_container, output
   
    # loading options, flaggs and arguments
    # YL TODO: make use of options
    options, pdbfiles = lib.loadOptions()

    propkaObj = molecular_container.Molecular_container(filename, options)

    # redirecting doesn't work?!
    with open('_propka.out', 'w') as fp:
        with redirect_stdout(fp):
            propkaObj.calculate_pka()
    # filename does not work because it is overwritten anyway in PROPKA
#    propkaObj.write_pka(filename='_propka.out')

    tmp = propkaObj.getFoldingProfile(conformation = 'AVR',
                                      reference    = 'neutral',
                                      direction    = 'folding',
                                      grid         = [0.,14.,0.1],
                                      options      =  options)

    pH_opt = tmp[1][0]

    return pH_opt
