import os
import openpyxl

from tklib.tkapplication import tkApplication
from tklib.tkutils import pint, pfloat, getarg, getintarg, getfloatarg


#================================
# global parameters
#================================

infile  = "defect_anlysis.xlsx"
outfile = "defect_out.xlsx"

ideal_EVBM = -0.736001
ideal_ECBM = 2.666158
ideal_Eg   = 3.4021589999999997

Etot_ideal  = -25.42422698
Etot_defect = -1220.02941528

defect_charge=-1.0

dEcorr = 0.06841088609937765
dEVBM  = 0.06330000000000102
dEBF   = 1.1558746736617502

defect_atom = ''
defect_site = ''

app = tkApplication()

#=============================
# Treat argments
#=============================
def usage(app = None):
    print("")
    print("Usage:")
    print("  (a)  python {} infile outfile EVBM Eg Etot(ideal) Etot(defect) q dEcorr dEVBM dEBF")

def updatevars():
    global infile, outfile
    global ideal_EVBM, ideal_Eg
    global Etot_ideal, Etot_defect
    global defect_charge
    global dEcorr, dEVBM, dEBF
    global defect_atom, defect_site

    infile        = getarg     (1, infile)
    outfile       = getarg     (2, outfile)
    ideal_EVBM    = getfloatarg(3, ideal_EVBM)
    ideal_Eg      = getfloatarg(4, ideal_Eg)
    Etot_ideal    = getfloatarg(5, Etot_ideal)
    Etot_defect   = getfloatarg(6, Etot_defect)
    defect_charge = getfloatarg(7, defect_charge)
    dEcorr        = getfloatarg(8, dEcorr)
    dEVBM         = getfloatarg(9, dEVBM)
    dEBF          = getfloatarg(10, dEBF)
    defect_atom   = getarg     (11, defect_atom)
    defect_site   = getarg     (12, defect_site)

def make_input():
    global infile

    print("")
    print("infile      : ", infile)
    print("outfile     : ", outfile)
    print("EVBM(ideal) : ", ideal_EVBM)
    print("Eg(ideal)   : ", ideal_Eg)
    print("Etot(ideal) : ", Etot_ideal)
    print("Etot(defect): ", Etot_defect)
    print("q(defect)   : ", defect_charge)
    print("charge correction     (dEcorr): ", dEcorr)
    print("VBM correction          (dEBF): ", dEBF)
    print("band filling correction (dEBF): ", dEBF)
    print("defect_atom: ", defect_atom)
    print("defect_site: ", defect_site)

    print("")
    if os.path.isfile(outfile):
        print(f"File {outfile} exists.")
        infile = outfile
    print(f"Read from [{infile}]")
    openpyxl.reader.excel.warnings.simplefilter('ignore')
    wb = openpyxl.load_workbook(infile, data_only = False, keep_vba = False)
    ws = wb.active

#    ws_values = wb_values.active

    row = 3
    for i in range(3, 100):
#        print(f"ws_out[C{i}]=", ws_out[f"C{i}"].value)
        if ws[f"C{i}"].value is None:
            row = i
            break
        else:
            atom = ws[f"C{i}"].value
            site = ws[f"D{i}"].value
            print(f"Defect {atom}_{site} is already recorded at line {i}")

    print(f"New defect [{defect_atom}_{defect_site}] is recorded at line {row}")
    ws["B4"] = pfloat(Etot_ideal)
    ws["B5"] = pfloat(ideal_EVBM)

    ws[f"C{row}"] = defect_atom
    ws[f"D{row}"] = defect_site
    ws[f"B{row}"] = pfloat(ideal_Eg)
    ws[f"F{row}"] = pfloat(Etot_defect)
    ws[f"E{row}"] = pfloat(defect_charge)
    ws[f"I{row}"] = pfloat(dEcorr)
    ws[f"J{row}"] = pfloat(dEVBM)
    ws[f"K{row}"] = -pfloat(dEBF)

    print("")
    print(f"Save to [{outfile}]")
    wb.save(outfile)

    app.terminate("", usage = usage, pause = True)


def main():
    
    updatevars()

    logfile = app.replace_path(outfile, template = ["{dirname}", "{filebody}-out.txt"])
    print("")
    print(f"Open logfile [{logfile}]")
    app.redirect(targets = ["stdout", logfile], mode = 'w')

    make_input()

    app.terminate("", usage = usage, pause = True)

if __name__ == "__main__":
    main()
