'''Print a banner'''

#  Copyright (C) 2017 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/>.

from ..data import references
#from .      import colours

def printBanner():
    ''''''

    import chemsh
    from sys        import stdout
    from subprocess import call, CalledProcessError, check_output, DEVNULL
    from time       import time as time_time 
    from time       import asctime, localtime
    from platform   import python_version
    from numpy      import version as npversion
    from .format    import printwrap

    linewidth = 70

    # default version code
    # version = 'Titanium'
    # release version
    version = '23.0.2'

    # YL 30/11/2023: it's really important for us developers and internal users to know which version we are running!
    try:
        if not bool(call('git rev-parse', shell=True, cwd=chemsh.CHEMSH_ROOT_DIR, stderr=DEVNULL)):
            version = 'Devel'
            # TD 13/03/2024 Set placeholder values in case the try block fails. Otherwise the variables could be unbound later
            git_branch = '*'
            git_commit = '*'
            git_author = '*'
            git_date = '*'
            lbuff = check_output('git branch', shell=True, cwd=chemsh.CHEMSH_ROOT_DIR).splitlines()
            git_detached = False
            for l in lbuff:
                branch_str = l.decode().strip()
                # The present branch will start with a *
                if branch_str.startswith('*'):
                    # we must deal with a detached repo (error otherwise)
                    if 'detached' in branch_str:
                        git_branch = branch_str.split()[-1].strip(')')
                        git_detached = True
                    else:
                        git_branch = branch_str.strip('* ')
            lbuff = check_output(f'git log -n 1 {git_branch}', shell=True, cwd=chemsh.CHEMSH_ROOT_DIR).splitlines()
            # extract information line by line
            for l in lbuff:
                if l.decode().strip().startswith('commit'):
                    git_commit = l.decode().strip().strip('commit ')[:8]
                if l.decode().strip().startswith('Author: '):
                    git_author = l.decode().strip().strip('Author: ')
                if l.decode().strip().startswith('Date: '):
                    git_date   = l.decode().strip().strip('Date:   ')
    # no Git installed
    except CalledProcessError:
        pass
            
    print("\n "+linewidth*"=")
    print(f" Py-ChemShell 2023 (version {version})")
    # YL 30/11/2023: the general users won't see this with a release version which is not a Git repo
    if version.startswith('Devel'):
        if git_detached:
            print(' Git branch: '+git_branch+' (detached)')
        else:
            print(' Git branch: '+git_branch)
        print(' Commit    : '+git_commit)
        print(' Authored  : '+git_author)
        print(' Dated     : '+git_date)
    print(" "+linewidth*"-")
    stdout.flush()

    print("", asctime(localtime(time_time())))
    print(" Compiler ", chemsh.CHEMSH_ARCH, "; Python ", python_version(), "; Numpy ", npversion.version, sep='')
    # YL 10/03/2021: CHEMSH_DEBUG should be obtained dynamically from chemsh because from `chemsh import CHEMSH_DEBUG`
    #                is statically defined when ChemShell initialises
    print(" Debug level", chemsh.CHEMSH_DEBUG)
    print(" "+linewidth*"-")

    print(" Please cite Py-ChemShell as:")
    printwrap(references.refs['chemsh-py'], indent='   ', prepend_blanc_line=False)

    print(" "+linewidth*"-")
    print(" www.chemshell.org")
    print(" "+linewidth*"=")
    print("")

    stdout.flush()


# TWK 21/12/2021 Added mini banners for interface calls
def printModuleBanner(title, level=1):
    '''Print formatted module banner.

    level=1: multiline large banner
    level=2: compact banner for frequent modules (e.g. interface calls)

    '''

    from sys import stdout

    l = len(title)

    strbuff =  '\n +' + '-'*(l+4) + '+\n'
    if level == 1:
        strbuff += ' |' + ' '*(l+4) + '|\n'
    strbuff += ' |  {}  |\n'.format(title)
    if level == 1:
        strbuff += ' |' + ' '*(l+4) + '|\n'
    strbuff += ' +' + '-'*(l+4) + '+\n'

    print(strbuff)
    stdout.flush()

    return strbuff
