#  Copyright (C) 2021 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.ukri.org>'

from itertools import takewhile, repeat

def getNumKeys(filename):

    try:
        with open(filename, 'rb') as fp:
#            # EOF if fp.raw.read() returns 0 (byte)
#            gbuff = takewhile(lambda x: x, (fp.raw.read(-1) for _ in repeat(None)))
            bbuff = fp.raw.readall()
            nleavings = bbuff.count(b'Leaving')
            nmakings  = bbuff.count(b'Making')
            nendings  = bbuff.count(b'make nwchem.o stubs.o')
        return nleavings, nmakings, nendings
    except FileNotFoundError:
        return 0, 0, 0


if __name__ == '__main__':

    from sys  import argv, maxsize, stdout
    from os   import path
    from time import sleep

    # get filename
    try:
        config, d2s, make = argv[1:4]
    except:
        exit(0)

    # we count the number of character keywords in the log files
    nleavings_full = { config:   2,
                       d2s   :  271,
                       make  : 1003 } # may vary on different systems
    nmakings_full  = { make  :  533 } # may vary on different systems
    nendings_full  = { make  :    1 }

    l_filenames = [ config, d2s, make ]

    for i, filename in enumerate(l_filenames):
        counter = 0
        while True:
            sleep(6)
            nleavings, nmakings, nendings = getNumKeys(filename)
            ratio_leave = int(nleavings/nleavings_full.get(filename, maxsize)*100)
            ratio_make  = int(nmakings /nmakings_full .get(filename, maxsize)*100)
            ratio_end   = int(nendings /nendings_full .get(filename, maxsize)*100)
            basename = path.splitext(path.basename(filename))[0]
            if ratio_leave >= 100:
                ratio_leave = 100
            print(f'Building {basename}... {ratio_leave}%'+' '*24, end='\r')
            stdout.flush()
            counter += 1
            # YL 05/07/2023: there must be something wrong if no progress in 10 mins
            if filename == l_filenames[2]:
                if counter > 99 and ratio_leave == 0:
                    with open(filename, 'r') as fp:
                        print(' >>> NWChem make.log:')
                        print(fp.read())
                        stdout.flush()
            # we consider it completed when the next file emerges; or for make.log when it reaches the end
            if (i<len(l_filenames)-1 and path.isfile(l_filenames[i+1])) or (ratio_make >= 100 and ratio_end >= 100):
                print(f'Building {basename}... 100%'+' '*24, end='\r')
                stdout.flush()
                print(f'{basename} successfully built.'+' '*24, end='\n')
                stdout.flush()
                break



