# -*- coding: utf-8 -*-
#***********************************************************************
# This file is part of OpenMolcas.                                     *
#                                                                      *
# OpenMolcas is free software; you can redistribute it and/or modify   *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties.   *
# For more details see the full text of the license in the file        *
# LICENSE or in <http://www.gnu.org/licenses/>.                        *
#                                                                      *
# Copyright (C) 2020-2022, Bruno Tenorio                               *
#***********************************************************************

import subprocess, time, re, fnmatch, sys, os, importlib.util, h5py
from os import listdir
from os.path import isfile, join

# auger_main.py needs python3 
# USE "pip install auger-oca" TO INSTALL the auger_oca package.
# This file can be copied around and executed anywhere as long as you (installed auger-oca with pip) 
# and have Project.rassi.h5 in the same directory.

ocaimport = importlib.util.find_spec('auger_oca') # First, Let me check if I have auger_oca packages
if ocaimport is None:
    print("auger_oca package is not installed. USE: pip install auger-oca ")
    sys.exit()

from auger_oca import *

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# ----------------------------------------------------------------------------------------------
# See README file
# It reads a file (or directory) containing 2-e rTDM files and rassi.h5 generated by OpenMolcas.
# A rassi.h5 file is used to get information on the basis set.
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#
def main():
    args = parseCL()    
    if args.inp:
        input_file = args.inp

        file_based,folder_based,RAES,NAES,NAES_T,NAES_S,\
        OCA_atom,OCA_center,OCA_line,benergy,totalSymmetry,symmetry,nbasf,nash,nmo,cmotab,tdmtab,ncmo,nbasft,\
        nasht,nosht,comtaboff,comtbasoff,comtbasoff2,comtcmoff,comtnashoff,cmob,cmoa,tdmab,dyson,\
        hd5_file,basis_id_hd5,element = my_variables(input_file)
#    
        driver_auger(input_file,RAES,NAES,NAES_T,NAES_S,\
        OCA_atom,OCA_line,benergy,totalSymmetry,symmetry,nbasf,cmotab,nbasft,comtaboff,comtbasoff,comtbasoff2,\
        comtcmoff,cmob,cmoa,nmo,tdmab,dyson,hd5_file,element,basis_id_hd5) # 

    if args.directory:
        n_files = 0
        myfiles = []
        pwd = os.getcwd() #to get the current working directory
        folder_exists = os.path.exists('auger_outputs')
        if folder_exists:
            subprocess.Popen('rm -r auger_outputs', stdout=subprocess.PIPE, shell=True)
            time.sleep(2)
        subprocess.Popen('mkdir auger_outputs', stdout=subprocess.PIPE, shell=True)
        myfiles0 = [f for f in listdir(args.directory) if isfile(join(args.directory, f))]
        myfiles = [n for n in myfiles0 if fnmatch.fnmatch(n, 'r2TM_*')]
        n_files = len(myfiles)

        for j in range(n_files):
            i=myfiles[j]
            rscr=args.directory
            r2TDM=re.sub(r'/$','', rscr) # a simple trick to deal with inputs '-d folder' or '-d folder/' without crashing
            input_file = r2TDM+"/"+i    # After removing '/' if given, then I add it back.

            file_based,folder_based,RAES,NAES,NAES_T,NAES_S,\
            OCA_atom,OCA_center,OCA_line,benergy,totalSymmetry,symmetry,nbasf,nash,nmo,cmotab,tdmtab,ncmo,nbasft,\
            nasht,nosht,comtaboff,comtbasoff,comtbasoff2,comtcmoff,comtnashoff,cmob,cmoa,tdmab,dyson,\
            hd5_file,basis_id_hd5,element = my_variables(input_file)
    
            driver_auger(i,RAES,NAES,NAES_T,NAES_S,\
            OCA_atom,OCA_line,benergy,totalSymmetry,symmetry,nbasf,cmotab,nbasft,comtaboff,comtbasoff,comtbasoff2,\
            comtcmoff,cmob,cmoa,nmo,tdmab,dyson,hd5_file,element,basis_id_hd5) #

        if args.parse_oca:
            subprocess.Popen('mv Auger_OCA.* auger_outputs', stdout=subprocess.PIPE, shell=True)
            time.sleep(3)
            if args.parse_spec:
                subprocess.Popen('for f in $(ls auger_outputs/Auger_OCA.*); do grep "Spectrum: BE(eV) and Intensity" $f \
 >> tmp.spectrum.out; done ; cat tmp.spectrum.out | cut -b 1-42 --complement >> auger.spectrum.out; rm -f tmp.spectrum.out',\
                stdout=subprocess.PIPE, shell=True) # another option is $bash oca.spectrum.sh auger_outputs
# The End!

if __name__ == "__main__":
    main()

