#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.13
# In conjunction with Tcl version 8.6
#    Aug 07, 2018 01:15:33 PM


######## SETUP
import sys
import os
import json
import configparser
import tkinter as tk
from tkinter import filedialog
import settingeditor_support
import xml.etree.ElementTree as ET
import ltc

try:
    from Tkinter import *
except ImportError:
    from tkinter import *
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
try:
    from Tkinter import *
except ImportError:
    from tkinter import *
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = Settings_Editor (root)
    settingeditor_support.init(root, top)
    root.mainloop()

w = None
def create_Settings_Editor(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = Settings_Editor (w)
    settingeditor_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Settings_Editor():
    global w
    w.destroy()
    w = None

######## VARIABLES / DECLATIONS
#### EXAMPLES / UNUSED
bsData1 = { #Default bsData ----------> example
    1: {
        "branchSetID": "bs1",
        "applyToTectonicRegionType": "Active Shallow Fault",
    }
}
ltBranch1 = { #Default ltBranch
    1: {
        1: {
            "branchSetID": "b11",
            "text": "GMPETable",
            "gmpe_table": "../gm_tables/WcrustFRjb_low_clC.hdf5",
            "uncertaintyWeight": "0.2"
        }
    }
}
ltData1 = { #Default ltData
    1: {
        "branchingLevelID": "bl1",
        "ltBranch": ltBranch1,
        "bsData": bsData1
    }
}

#### VARIABLES
## JOB.INI
specY = 25 # y size per item set -> job.ini
numMade = 0 # amount of item sets -> job.ini
ifPreset = 1 # -> job.ini

#### DICTIONARIES / LISTS
## CORE
opFiles = { #operation files, for easy modification / reference
    "gmpehandler": "gmpe-handler.py",
    "jobhandler": "job-handler.py",
    "smlthandler": "smlt-handler.py"
}

## GMPE
bsData = {} #Default bsData
ltBranch = {} #Default ltBranch
ltData = {} #Default ltData}
## JOB.INI
atxtbox = {} # Dictionary of all job.ini textboxes / keys
v = { # job.ini array
    #general
    1: {"description": ""},
    2: {"calculation_mode": ""},
    3: {"random_seed": ""},
    #geometry
    4: {"sites_csv": ""},
    #logic_tree
    5: {"number_of_logic_tree_samples": ""},
    #Erf
    6: {"rupture_mesh_spacing": ""},
    7: {"width_of_mfd_bin": ""},
    8: {"area_source_discretization": ""},
    #site_params
    9: {"reference_vs30_type": ""},
    10: {"reference_vs30_value": ""},
    11: {"reference_depth_to_2pt5km_per_sec": ""},
    12: {"reference_depth_to_1pt0km_per_sec": ""},
    #calculation
    13: {"source_model_logic_tree_file": ""},
    14: {"gsim_logic_tree_file": ""},
    15: {"investigation_time": ""},
    16: {"intensity_measure_types_and_levels": ""},
    17: {"truncation_level": ""},
    18: {"maximum_distance": ""},
    #output
    19: {"export_dir": ""},
    20: {"mean_hazard_curves": ""},
    21: {"quantile_hazard_curves": ""},
    22: {"hazard_maps": ""},
    23: {"uniform_hazard_spectra": ""},
    24: {"poes": ""}
}

######## GUI STUFF ---> TKINTER GUI CREATION / MODIFICATION

######## CORE FUNCTIONS ---> NON-BINDED, NON-PAYLOAD
def deleteObject(type, obj):
    print("???")
def pToOutput(text):
    output.configure(state=NORMAL)
    output.delete(1.0, "end")
    output.insert("end", text)
    output.configure(state=DISABLED)
def parseOut(Data): # display info on screen
    es = ""
    for x in range(0,len(Data)): #Parse the Branch Sets!!!
        if len(Data) != 0:
            #print(len(Data))
            x=x+1

        curBlock = Data[x]
        bsData2 = curBlock["bsData"][x]
        es = es+"\n Branch Set "+str(x)+" (Branch Set ID:  "+bsData2["branchSetID"]+") (Branching Level ID: "+curBlock["branchingLevelID"]+") (Tectonic Region Type: "+bsData2["applyToTectonicRegionType"]+")"
        for z in range(0, len(curBlock["ltBranch"][x])): #Parse each branch set's branches
            z = z+1
            curChild = curBlock["ltBranch"][x][z]
            es = es+"\n    -> Branch "+str(z)+" (Branch ID: "+curChild["branchSetID"]+") (GMPE Table: "+curChild["gmpe_table"]+") (Uncertainty Weight: "+curChild["uncertaintyWeight"]+")"
        print(es)
    pToOutput(es)
def setoutput(var):
    global output
    output = var

######## PAYLOAD FUNCTIONS ---> FUNCTIONS THAT ARE USED BY BOUND FUNCTIONS
def newBranchSet(branchSetID, applyToTectonicRegionType, branchingLevelID):
    global ltData
    global bsData
    global output

    if branchingLevelID == "" or branchingLevelID == " ":
        branchingLevelID = "bl"+str(len(ltData)+1)
    if branchSetID == "" or branchSetID == " ":
        branchSetID = "bs"+str(len(bsData)+1)
        print("Branch Set ID -> "+branchSetID+"\n")

    ltData[len(ltData)+1] = {
        "branchingLevelID": branchingLevelID,
        "ltBranch": ltBranch,
        "bsData": bsData
    }
    bsData[len(bsData)+1] = {
        "branchSetID": branchSetID,
        "applyToTectonicRegionType":applyToTectonicRegionType
    }
    ltBranch[len(ltBranch)+1] = {}
    parseOut(ltData)
def newBranch(bsID, gmpe_table, uncertaintyWeight):
    global ltData
    impNum = 0
    bsData5 = ltData[1]["bsData"]
    ltBranch5 = ltData[1]["ltBranch"]
    for x in range(0,len(bsData5)): #get the branchset number
        x = x+1
        y = bsData5[x]
        if y["branchSetID"] == bsID:
            impNum = x
    branchSet = ltBranch5[impNum]
    branchSet[len(branchSet)+1] = {
        "branchSetID": "b"+str(impNum)+str(len(branchSet)+1),
        "text": "GMPETable",
        "gmpe_table": gmpe_table,
        'uncertaintyWeight': uncertaintyWeight
    }
    print("Test -> "+json.dumps(ltData))
    parseOut(ltData)
def deleteFunc(BoS, bsid, blid): # function that deletes whatever
    #print("BoS -> "+BoS)
    #print("Set ID -> "+bsid)
    #print("Branch ID -> "+blid)
    if BoS == "branch":
        for a in range(0,len(bsData)):
            a = a + 1
            #print(a)
            curBranch = bsData[a]
            if curBranch["branchSetID"] == bsid:
                for z in range(0, len(ltBranch[a])):
                    z=z+1
                    cB2 = ltBranch[a][z]
                    #print(cB2["branchSetID"]+" : "+blid)
                    if cB2["branchSetID"] == blid:
                        del(ltBranch[a][z])
                        parseOut(ltData)
                #print("bsData -> "+bsData)
                #print("ltBranch -> "+ltBranch)
                #print("ltData -> "+ltData)
    elif BoS == "set":
        for a in range(0,len(bsData)):
            a = a + 1
            print(bsData)
            curSet = bsData[a]
            if curSet["branchSetID"] == bsid:
                #print('yee')
                del(ltBranch[a])
                del(bsData[a])
                del(ltData[a])
                parseOut(ltData)
def editWindow(BoS,bsid,bid): # create window that edits something
    #print("BoS : "+BoS)
    #print("bsid : "+bsid)
    #print("bid : "+bid)

    #tkinter stuff
    _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
    _fgcolor = '#000000'  # X11 color: 'black'
    _compcolor = '#d9d9d9' # X11 color: 'gray85'
    _ana1color = '#d9d9d9' # X11 color: 'gray85'
    _ana2color = '#d9d9d9' # X11 color: 'gray85'
    style = ttk.Style()
    if sys.platform == "win32":
        style.theme_use('winnative')
    style.configure('.',background=_bgcolor)
    style.configure('.',foreground=_fgcolor)
    style.configure('.',font="TkDefaultFont")
    style.map('.',background=[('selected', _compcolor), ('active',_ana2color)])
    top = tk.Tk()
    top.geometry("425x70")
    top.title("Editing ...")
    top.configure(background="#d9d9d9")
    top.configure(highlightbackground="#d9d9d9")
    top.configure(highlightcolor="black")

    #payload
    bsnumber = 0
    bnumber = 0

    for x in range(0,len(bsData)):
        x=x+1
        cur = bsData[x]
        if cur["branchSetID"] == bsid:
            bsnumber = x
            if BoS=="branch":
                curSet = ltBranch[bsnumber]
                for z in range(0,len(curSet)):
                    z=z+1
                    if curSet[z]["branchSetID"] == bid:
                        bnumber = z

    setValues = {
        1: {"applyToTectonicRegionType": bsData[bsnumber]["applyToTectonicRegionType"]}
    }
    branchValues = {}
    if BoS == "branch":
        branchValues = {
            1: {"gmpe_table": ltBranch[bsnumber][bnumber]["gmpe_table"]},
            2: {"uncertaintyWeight": ltBranch[bsnumber][bnumber]["uncertaintyWeight"]}
        }

    numMade2 = 0
    boxes = []
    if BoS == "branch":
        specY2 = 30
        for x in range(0,len(branchValues)):
            x=x+1
            curSelect = branchValues[x]
            for key in curSelect:
                numMade2 = x
                text_1 = ttk.Label(top)
                box_1 = ttk.Entry(top)
                if x == 1:
                    text_1.place(x=0, y=5, height=19, width=136)
                    box_1.place(relx=0.54, y=0, height=20, relwidth=0.45)
                else:
                    burger = 5+30*(x-1)
                    box_1.place(relx=0.54, y=burger, height=20, relwidth=0.45)
                    text_1.place(x=0.01, y=burger, height=19, width=136)
                text_1.configure(background="#d9d9d9")
                text_1.configure(foreground="#000000")
                text_1.configure(font="TkDefaultFont")
                text_1.configure(relief=FLAT)
                text_1.configure(text=key)
                box_1.configure(takefocus="")
                box_1.configure(cursor="ibeam")
                boxes.append({"name": str(text_1.cget("text")), "box": box_1})
    elif BoS == "set":
        specY2 = 30
        for x in range(0,len(setValues)):
            x=x+1
            curSelect = setValues[x]
            for key in curSelect:
                numMade2 = x
                text_1 = ttk.Label(top)
                box_1 = ttk.Entry(top)
                if x == 1:
                    text_1.place(x=0, y=5, height=19, width=136)
                    box_1.place(relx=0.54, y=0, height=20, relwidth=0.45)
                else:
                    burger = 5+30*(x-1)
                    box_1.place(relx=0.54, y=burger, height=20, relwidth=0.45)
                    text_1.place(x=0.01, y=burger, height=19, width=150)
                text_1.configure(background="#d9d9d9")
                text_1.configure(foreground="#000000")
                text_1.configure(font="TkDefaultFont")
                text_1.configure(relief=FLAT)
                text_1.configure(text=key)
                box_1.configure(takefocus="")
                box_1.configure(cursor="ibeam")
                boxes.append({"name": str(text_1.cget("text")), "box": box_1})
    top.geometry("425x"+str(30*numMade2+30))

    leetNumber = int(30*numMade2)
    print("leetNumber -> "+str(leetNumber))
    finishButton = Button(top)
    def onClick2():
        if BoS == "branch":
            for j in range(0,len(boxes)):
                bSet = boxes[j]
                if bSet["name"] == "gmpe_table":
                    branchValues[1]["gmpe_table"] = bSet["box"].get()
                elif bSet["name"] == "uncertaintyWeight":
                    branchValues[2]["uncertaintyWeight"] = bSet["box"].get()
            deleteFunc(BoS,bsid,bid)
            for t in range(0,len(branchValues)):
                t=t+1
                print(branchValues[t])
            newBranch(bsid,branchValues[1]["gmpe_table"],branchValues[2]["uncertaintyWeight"])
        elif BoS == "set":
            for j in range(0,len(boxes)):
                bSet = boxes[j]
                if bSet["name"] == "applyToTectonicRegionType":
                    setValues[1]["applyToTectonicRegionType"] = bSet["box"].get()
            deleteFunc(BoS,bsid,bid)
            newBranchSet(bsid,setValues[1]["applyToTectonicRegionType"],bid)
        top.destroy()
    finishButton.place(y=leetNumber,relx=0.39, rely=0, height=25, width=90)
    finishButton.configure(activebackground="#d9d9d9")
    finishButton.configure(activeforeground="#000000")
    finishButton.configure(background="#d9d9d9")
    finishButton.configure(disabledforeground="#a3a3a3")
    finishButton.configure(foreground="#000000")
    finishButton.configure(highlightbackground="#d9d9d9")
    finishButton.configure(highlightcolor="black")
    finishButton.configure(pady="0")
    finishButton.configure(relief=GROOVE)
    finishButton.configure(text='''Done''')
    finishButton.configure(command=onClick2)
def openJobFunction(file_path):
    cfg = configparser.ConfigParser()
    cfg.read(file_path)
    sections = cfg.sections()
    for each_section in sections:
        for each_key, each_val in cfg.items(each_section):
            for x in range(0,len(v)):
                x=x+1
                curVal = v[x]
                for key in curVal:
                    curSel = curVal[key]
                    if each_key == key:
                        curVal[key] = each_val
                        #print(key+" : "+each_val)

    for key2 in atxtbox:
        curBox1 = atxtbox[key2]
        curBox1.delete(0, END)
        print("Key2 -> "+key2)
        for y in range(len(v)):
            y=y+1
            for key3 in v[y]:
                if key3 == key2:
                    curBox1.insert(0, v[y][key2])

######## BOUND FUNCTIONS ---> BOUND TO BUTTONS/OTHER EVENTS
def editPopup(): # creates selection window for editing
    _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
    _fgcolor = '#000000'  # X11 color: 'black'
    _compcolor = '#d9d9d9' # X11 color: 'gray85'
    _ana1color = '#d9d9d9' # X11 color: 'gray85'
    _ana2color = '#d9d9d9' # X11 color: 'gray85'
    style = ttk.Style()
    if sys.platform == "win32":
        style.theme_use('winnative')
    style.configure('.',background=_bgcolor)
    style.configure('.',foreground=_fgcolor)
    style.configure('.',font="TkDefaultFont")
    style.map('.',background=
        [('selected', _compcolor), ('active',_ana2color)])
    top = tk.Tk()
    top.geometry("425x130+789+438")
    top.title("Select what to edit ...")
    top.configure(background="#d9d9d9")
    top.configure(highlightbackground="#d9d9d9")
    top.configure(highlightcolor="black")

    blIDtxt = ttk.Label(top)
    blIDtxt.place(relx=0.01, rely=0.31, height=19, width=136)
    blIDtxt.configure(background="#d9d9d9")
    blIDtxt.configure(foreground="#000000")
    blIDtxt.configure(font="TkDefaultFont")
    blIDtxt.configure(relief=FLAT)
    blIDtxt.configure(text='''Set/Branch ID''')

    blIDbox = ttk.Entry(top)
    blIDbox.place(relx=0.54, rely=0.31, relheight=0.15, relwidth=0.45)
    blIDbox.configure(takefocus="")
    blIDbox.configure(cursor="ibeam")


    BorSVar = tk.IntVar()
    BorSVar.set(1)

    def sbBor():
        BorSVar.set(0)
        #print(BorSVar.get())
    def bbBor():
        BorSVar.set(1)
        #print(BorSVar.get())


    SetButton = tk.Radiobutton(top,
        value=0,
        variable=BorSVar,
        command=sbBor,
        activebackground="#d9d9d9",
        activeforeground="#000000",
        background="#d9d9d9",
        disabledforeground="#a3a3a3",
        foreground="#000000",
        highlightbackground="#d9d9d9",
        highlightcolor="black",
        justify=LEFT,
        text="Set"
    )
    SetButton.place(relx=0.54, rely=0.08, relheight=0.19, relwidth=0.1)



    BranchButton = tk.Radiobutton(top,
        value=1,
        variable=BorSVar,
        command=bbBor,
        activebackground="#d9d9d9",
        activeforeground="#000000",
        background="#d9d9d9",
        disabledforeground="#a3a3a3",
        foreground="#000000",
        highlightbackground="#d9d9d9",
        highlightcolor="black",
        justify=LEFT,
        text="Branch"
    )
    BranchButton.place(relx=0.82, rely=0.08, relheight=0.19, relwidth=0.15)


    def startEdit():
        #print("FOR BURGER??")
        blid1 = blIDbox.get()
        blid2 = blIDbox_2.get()
        top.destroy()
        print(BorSVar.get())
        if BorSVar.get() == 1:
            print("1")
            editWindow("branch", blid1, blid2)
        elif BorSVar.get() == 0:
            print("0")
            editWindow("set", blid1, "")


    def onClick():
        startEdit()


    createButton = Button(top)
    createButton.place(relx=0.39, rely=0.77, height=25, width=90)
    createButton.configure(activebackground="#d9d9d9")
    createButton.configure(activeforeground="#000000")
    createButton.configure(background="#d9d9d9")
    createButton.configure(disabledforeground="#a3a3a3")
    createButton.configure(foreground="#000000")
    createButton.configure(highlightbackground="#d9d9d9")
    createButton.configure(highlightcolor="black")
    createButton.configure(pady="0")
    createButton.configure(relief=GROOVE)
    createButton.configure(command=onClick)
    createButton.configure(text='''Edit''')




    SorB = ttk.Label(top)
    SorB.place(relx=0.01, rely=0.08, height=19, width=136)
    SorB.configure(background="#d9d9d9")
    SorB.configure(foreground="#000000")
    SorB.configure(font="TkDefaultFont")
    SorB.configure(relief=FLAT)
    SorB.configure(text='''Set or Branch''')





    blIDtxt_1 = ttk.Label(top)
    blIDtxt_1.place(relx=0.01, rely=0.54, height=19, width=200)
    blIDtxt_1.configure(background="#d9d9d9")
    blIDtxt_1.configure(foreground="#000000")
    blIDtxt_1.configure(font="TkDefaultFont")
    blIDtxt_1.configure(relief=FLAT)
    blIDtxt_1.configure(text="Branch ID (ignore if set)")

    blIDbox_2 = ttk.Entry(top)
    blIDbox_2.place(relx=0.54, rely=0.54, relheight=0.15, relwidth=0.45)

    blIDbox_2.configure(takefocus="")
    blIDbox_2.configure(cursor="ibeam")
def deletePopup(): #Deletetion POPUP
    _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
    _fgcolor = '#000000'  # X11 color: 'black'
    _compcolor = '#d9d9d9' # X11 color: 'gray85'
    _ana1color = '#d9d9d9' # X11 color: 'gray85'
    _ana2color = '#d9d9d9' # X11 color: 'gray85'
    style = ttk.Style()
    if sys.platform == "win32":
        style.theme_use('winnative')
    style.configure('.',background=_bgcolor)
    style.configure('.',foreground=_fgcolor)
    style.configure('.',font="TkDefaultFont")
    style.map('.',background=[('selected', _compcolor), ('active',_ana2color)])
    top = tk.Tk()
    top.geometry("425x130+789+438")
    top.title("Delete ...")
    top.configure(background="#d9d9d9")
    top.configure(highlightbackground="#d9d9d9")
    top.configure(highlightcolor="black")

    blIDtxt = ttk.Label(top)
    blIDtxt.place(relx=0.01, rely=0.31, height=19, width=136)
    blIDtxt.configure(background="#d9d9d9")
    blIDtxt.configure(foreground="#000000")
    blIDtxt.configure(font="TkDefaultFont")
    blIDtxt.configure(relief=FLAT)
    blIDtxt.configure(text='''Set ID''')

    blIDbox = ttk.Entry(top)
    blIDbox.place(relx=0.54, rely=0.31, relheight=0.15, relwidth=0.45)
    blIDbox.configure(takefocus="")
    blIDbox.configure(cursor="ibeam")


    BorSVar = tk.IntVar()
    BorSVar.set(1)

    def sbBor():
        BorSVar.set(0)
        #print(BorSVar.get())
    def bbBor():
        BorSVar.set(1)
        #print(BorSVar.get())


    SetButton = tk.Radiobutton(top,
        value=0,
        variable=BorSVar,
        command=sbBor,
        activebackground="#d9d9d9",
        activeforeground="#000000",
        background="#d9d9d9",
        disabledforeground="#a3a3a3",
        foreground="#000000",
        highlightbackground="#d9d9d9",
        highlightcolor="black",
        justify=LEFT,
        text="Set"
    )
    SetButton.place(relx=0.54, rely=0.08, relheight=0.19, relwidth=0.1)

    BranchButton = tk.Radiobutton(top,
        value=1,
        variable=BorSVar,
        command=bbBor,
        activebackground="#d9d9d9",
        activeforeground="#000000",
        background="#d9d9d9",
        disabledforeground="#a3a3a3",
        foreground="#000000",
        highlightbackground="#d9d9d9",
        highlightcolor="black",
        justify=LEFT,
        text="Branch"
    )
    BranchButton.place(relx=0.82, rely=0.08, relheight=0.19, relwidth=0.15)


    def dele():
        print("FOR BURGER??")
        print(BorSVar.get())
        if BorSVar.get() == 1:
            print("1")
            deleteFunc("branch", blIDbox.get(), blIDbox_2.get())
        elif BorSVar.get() == 0:
            print("0")
            deleteFunc("set", blIDbox.get(), "")

    def onClick():
        dele()
        top.destroy()

    createButton = Button(top)
    createButton.place(relx=0.39, rely=0.77, height=25, width=90)
    createButton.configure(activebackground="#d9d9d9")
    createButton.configure(activeforeground="#000000")
    createButton.configure(background="#d9d9d9")
    createButton.configure(disabledforeground="#a3a3a3")
    createButton.configure(foreground="#000000")
    createButton.configure(highlightbackground="#d9d9d9")
    createButton.configure(highlightcolor="black")
    createButton.configure(pady="0")
    createButton.configure(relief=GROOVE)
    createButton.configure(command=onClick)
    createButton.configure(text='''Delete''')

    def onClick():
        dele()
        top.destroy()


    SorB = ttk.Label(top)
    SorB.place(relx=0.01, rely=0.08, height=19, width=136)
    SorB.configure(background="#d9d9d9")
    SorB.configure(foreground="#000000")
    SorB.configure(font="TkDefaultFont")
    SorB.configure(relief=FLAT)
    SorB.configure(text='''Set or Branch''')





    blIDtxt_1 = ttk.Label(top)
    blIDtxt_1.place(relx=0.01, rely=0.54, height=19, width=200)
    blIDtxt_1.configure(background="#d9d9d9")
    blIDtxt_1.configure(foreground="#000000")
    blIDtxt_1.configure(font="TkDefaultFont")
    blIDtxt_1.configure(relief=FLAT)
    blIDtxt_1.configure(text='''Branch ID (Ignore if deleting set)''')

    blIDbox_2 = ttk.Entry(top)
    blIDbox_2.place(relx=0.54, rely=0.54, relheight=0.15, relwidth=0.45)

    blIDbox_2.configure(takefocus="")
    blIDbox_2.configure(cursor="ibeam")
def nbsPopup(): #New Branch Set Popup Window
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#d9d9d9' # X11 color: 'gray85'
        style = ttk.Style()
        if sys.platform == "win32":
            style.theme_use('winnative')
        style.configure('.',background=_bgcolor)
        style.configure('.',foreground=_fgcolor)
        style.configure('.',font="TkDefaultFont")
        style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])
        top = tk.Tk()
        top.geometry("425x154+387+368")
        top.title("Create New Branch Set")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        #branch set txt label
        bsIDtxt = ttk.Label(top)
        bsIDtxt.place(relx=0.01, rely=0.06, height=20, width=86)
        bsIDtxt.configure(background="#d9d9d9")
        bsIDtxt.configure(foreground="#000000")
        bsIDtxt.configure(font="TkDefaultFont")
        bsIDtxt.configure(relief=FLAT)
        bsIDtxt.configure(text='''Branch Set ID''')
        #branch set id txt box
        bsIDbox = ttk.Entry(top)
        bsIDbox.place(relx=0.54, rely=0.06, relheight=0.13, relwidth=0.45)
        bsIDbox.configure(takefocus="")
        bsIDbox.configure(cursor="ibeam")

        blIDtxt = ttk.Label(top)
        blIDtxt.place(relx=0.01, rely=0.26, height=19, width=136)
        blIDtxt.configure(background="#d9d9d9")
        blIDtxt.configure(foreground="#000000")
        blIDtxt.configure(font="TkDefaultFont")
        blIDtxt.configure(relief=FLAT)
        blIDtxt.configure(text='''Branching Level ID''')

        blIDbox = ttk.Entry(top)
        blIDbox.place(relx=0.54, rely=0.26, relheight=0.13, relwidth=0.45)
        blIDbox.configure(takefocus="")
        blIDbox.configure(cursor="ibeam")

        attrtTXT = ttk.Label(top)
        attrtTXT.place(relx=0.28, rely=0.45, height=19, width=180)
        attrtTXT.configure(background="#d9d9d9")
        attrtTXT.configure(foreground="#000000")
        attrtTXT.configure(font="TkDefaultFont")
        attrtTXT.configure(relief=FLAT)
        attrtTXT.configure(text='''Apply To Tectonic Region Type''')

        attrtBOX = ttk.Entry(top)
        attrtBOX.place(relx=0.01, rely=0.58, relheight=0.13, relwidth=0.98)
        attrtBOX.configure(takefocus="")
        attrtBOX.configure(cursor="ibeam")


        createButton = Button(top)
        createButton.place(relx=0.39, rely=0.78, height=25, width=90)
        createButton.configure(activebackground="#d9d9d9")
        createButton.configure(activeforeground="#000000")
        createButton.configure(background="#d9d9d9")
        createButton.configure(disabledforeground="#a3a3a3")
        createButton.configure(foreground="#000000")
        createButton.configure(highlightbackground="#d9d9d9")
        createButton.configure(highlightcolor="black")
        createButton.configure(pady="0")
        createButton.configure(relief=GROOVE)
        createButton.configure(text='''Create''')
        def onClick():
            newBranchSet(bsIDbox.get(), attrtBOX.get(), blIDbox.get())
            top.destroy()
        createButton.configure(command=onClick)
def nbPopup(): #New Branch Set Popup Window
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#d9d9d9' # X11 color: 'gray85'
        style = ttk.Style()
        if sys.platform == "win32":
            style.theme_use('winnative')
        style.configure('.',background=_bgcolor)
        style.configure('.',foreground=_fgcolor)
        style.configure('.',font="TkDefaultFont")
        style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])
        top = tk.Tk()
        top.geometry("425x154+387+368")
        top.title("Create New Branch")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        #branch set txt label
        bsIDtxt = ttk.Label(top)
        bsIDtxt.place(relx=0.01, rely=0.06, height=20, width=86)
        bsIDtxt.configure(background="#d9d9d9")
        bsIDtxt.configure(foreground="#000000")
        bsIDtxt.configure(font="TkDefaultFont")
        bsIDtxt.configure(relief=FLAT)
        bsIDtxt.configure(text='Branch Set ID')
        #branch set id txt box
        bsIDbox = ttk.Entry(top)
        bsIDbox.place(relx=0.54, rely=0.06, relheight=0.13, relwidth=0.45)
        bsIDbox.configure(takefocus="")
        bsIDbox.configure(cursor="ibeam")

        blIDtxt = ttk.Label(top)
        blIDtxt.place(relx=0.01, rely=0.26, height=19, width=136)
        blIDtxt.configure(background="#d9d9d9")
        blIDtxt.configure(foreground="#000000")
        blIDtxt.configure(font="TkDefaultFont")
        blIDtxt.configure(relief=FLAT)
        blIDtxt.configure(text='Uncertainty Weight')

        blIDbox = ttk.Entry(top)
        blIDbox.place(relx=0.54, rely=0.26, relheight=0.13, relwidth=0.45)
        blIDbox.configure(takefocus="")
        blIDbox.configure(cursor="ibeam")

        attrtTXT = ttk.Label(top)
        attrtTXT.place(relx=0.42, rely=0.45, height=19, width=180)
        attrtTXT.configure(background="#d9d9d9")
        attrtTXT.configure(foreground="#000000")
        attrtTXT.configure(font="TkDefaultFont")
        attrtTXT.configure(relief=FLAT)
        attrtTXT.configure(text='''gmpe_table''')

        attrtBOX = ttk.Entry(top)
        attrtBOX.place(relx=0.01, rely=0.58, relheight=0.13, relwidth=0.98)
        attrtBOX.configure(takefocus="")
        attrtBOX.configure(cursor="ibeam")


        createButton = Button(top)
        createButton.place(relx=0.39, rely=0.78, height=25, width=90)
        createButton.configure(activebackground="#d9d9d9")
        createButton.configure(activeforeground="#000000")
        createButton.configure(background="#d9d9d9")
        createButton.configure(disabledforeground="#a3a3a3")
        createButton.configure(foreground="#000000")
        createButton.configure(highlightbackground="#d9d9d9")
        createButton.configure(highlightcolor="black")
        createButton.configure(pady="0")
        createButton.configure(relief=GROOVE)
        createButton.configure(text='''Create''')
        def onClick():
            newBranch(bsIDbox.get(), attrtBOX.get(), blIDbox.get())
            top.destroy()
        createButton.configure(command=onClick)
def saveFunction(): #saves bs as json table
    toExp1 = json.dumps(ltData)
    fileName1 = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("JSON file","*.json"), ("all files","*.*")))
    if fileName1 == "":
        return'yeet'

    lgt = len(fileName1)
    if lgt > 4:
        if fileName1[(lgt-4):lgt] != ".json":
            fileName1 = fileName1+".json"
    fileName1 = fileName1+".json"
    with open(fileName1, 'w') as fp:
        json.dump(ltData, fp)
    fp.close()
    print("toExp1 -> "+toExp1)
def openFunction(): #opens jason table
    global ltData
    global bsData
    global ltBranch

    ltData = {}
    trashdata = {} #temp bsData
    trashBranch = {} #temp branch set
    tempdata = {} #temp ltData
    curBSet = {} #temp branch(es)

    file_path = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("JSON file","*.json"), ("all files","*.*")))
    if file_path == "":
        return'yeet'
    print("\nfile_path -> "+file_path)
    fileSp = open(file_path, "r")
    content = json.load(fileSp)
    fileSp.close()

    ltBranch5 = content["1"]["ltBranch"]
    bsData5 = content["1"]["bsData"]


    for key,val in content.items():
        curBSet = {} # reset dict

        tempdata[int(key)] = val # Create the ltData
        tempdata[int(key)]["ltBranch"] = {} #clearing them
        tempdata[int(key)]["bsData"] = {} #clearing them
        trashdata[int(key)] = bsData5[key] # Create a brand new bsData

        for k,v in ltBranch5[key].items(): # Loop through the current set of branches
            curBSet[int(key)] = v # Copy over the value of that branch
        trashBranch[int(key)] = curBSet # Add to the branch set

    tempdata[int(key)]["ltBranch"] = trashBranch
    tempdata[int(key)]["bsData"] = trashdata
    print("\ntempdata -> "+str(tempdata))




    ltData = tempdata
    bsData = tempdata[int(key)]["bsData"]
    ltBranch = tempdata[int(key)]["ltBranch"]

    print("\nltData -> "+str(ltData))
    parseOut(ltData)
def openJobStart(): #open function bound to job.ini open button
    file_path = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("INI file","*.ini"), ("all files","*.*")))
    if file_path == "":
        return'No file selected'
    print("\nfile_path -> "+file_path)
    openJobFunction(file_path)

######## MAIN
class Settings_Editor: #main window
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#d9d9d9' # X11 color: 'gray85'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.configure('.',font="TkDefaultFont")
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])

        top.geometry("600x448+733+301")
        top.title("Settings Editor")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        top.resizable(False, False)

        def export(data): # function that exports the branch json
            toExp = json.dumps(json.dumps(ltData))
            top.filename = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("XML file","*.xml"), ("all files","*.*")))
            if top.filename == "":
                return 0
            top.filename = top.filename+".xml"
            os.system(opFiles.get("gmpehandler")+' -output "'+top.filename+'" -ltd '+toExp)

        def tab_changed(event):
            curTab = self.notebook.index("current")
            if curTab == 1:
                top.geometry("670x650")

            else:
                top.geometry("600x448")


        self.style.configure('TNotebook.Tab', background=_bgcolor)
        self.style.configure('TNotebook.Tab', foreground=_fgcolor)
        self.style.map('TNotebook.Tab', background=
            [('selected', _compcolor), ('active',_ana2color)])
        self.notebook = ttk.Notebook(top)
        self.notebook.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
        self.notebook_t0 = Frame(self.notebook)
        self.notebook.add(self.notebook_t0, padding=3)
        self.notebook.tab(0, text="GMPE Logic Tree", compound="left"
                ,underline="-1",)
        self.notebook.bind("<<NotebookTabChanged>>", tab_changed)

        self.notebook_t0.configure(background="#d9d9d9")
        self.notebook_t0.configure(highlightbackground="#d9d9d9")
        self.notebook_t0.configure(highlightcolor="black")

        self.notebook_t1 = Frame(self.notebook)
        self.notebook.add(self.notebook_t1, padding=3)
        self.notebook.tab(1, text="Job.ini",compound="left",underline="-1",)
        self.notebook_t1.configure(background="#d9d9d9")
        self.notebook_t1.configure(highlightbackground="#d9d9d9")
        self.notebook_t1.configure(highlightcolor="black")

        self.Scrolledtext1 = ScrolledText(self.notebook_t0)
        self.Scrolledtext1.place(relx=0.0, rely=0.07, relheight=0.76
                , relwidth=1.0)
        self.Scrolledtext1.configure(background="white")
        self.Scrolledtext1.configure(font="TkTextFont")
        self.Scrolledtext1.configure(foreground="black")
        self.Scrolledtext1.configure(highlightbackground="#d9d9d9")
        self.Scrolledtext1.configure(highlightcolor="black")
        self.Scrolledtext1.configure(insertbackground="black")
        self.Scrolledtext1.configure(insertborderwidth="3")
        self.Scrolledtext1.configure(selectbackground="#c4c4c4")
        self.Scrolledtext1.configure(selectforeground="black")
        self.Scrolledtext1.configure(state=DISABLED)
        self.Scrolledtext1.configure(width=10)
        self.Scrolledtext1.configure(wrap=NONE)
        setoutput(self.Scrolledtext1)

        self.Export = Button(self.notebook_t0)
        self.Export.place(relx=0, rely=0.01, height=20, relwidth=0.333)
        self.Export.configure(activebackground="#bababa")
        self.Export.configure(activeforeground="#000000")
        self.Export.configure(background="#bababa")
        self.Export.configure(disabledforeground="#a3a3a3")
        self.Export.configure(foreground="#000000")
        self.Export.configure(highlightbackground="#d9d9d9")
        self.Export.configure(highlightcolor="black")
        self.Export.configure(pady="0")
        self.Export.configure(relief=FLAT)
        self.Export.configure(text='''Export''')
        self.Export.configure(command=lambda: export(ltData))

        '''
        self.Import = Button(self.notebook_t0)
        self.Import.place(relx=0.25, rely=0.01, height=21, relwidth=0.25)
        self.Import.configure(activebackground="#bababa")
        self.Import.configure(activeforeground="#000000")
        self.Import.configure(background="#bababa")
        self.Import.configure(disabledforeground="#a3a3a3")
        self.Import.configure(foreground="#000000")
        self.Import.configure(highlightbackground="#d9d9d9")
        self.Import.configure(highlightcolor="black")
        self.Import.configure(pady="0")
        self.Import.configure(relief=FLAT)
        self.Import.configure(text="Import")
        self.Import.configure(command=importFunction)
        '''

        self.open = Button(self.notebook_t0)
        self.open.place(relx=0.333, rely=0.01, height=20, relwidth=0.333)
        self.open.configure(activebackground="#bababa")
        self.open.configure(activeforeground="#000000")
        self.open.configure(background="#bababa")
        self.open.configure(disabledforeground="#a3a3a3")
        self.open.configure(foreground="#000000")
        self.open.configure(highlightbackground="#d9d9d9")
        self.open.configure(highlightcolor="black")
        self.open.configure(pady="0")
        self.open.configure(relief=FLAT)
        self.open.configure(text="Open")
        self.open.configure(command=openFunction)

        self.save = Button(self.notebook_t0)
        self.save.place(relx=0.666, rely=0.01, height=20, relwidth=0.333)
        self.save.configure(activebackground="#bababa")
        self.save.configure(activeforeground="#000000")
        self.save.configure(background="#bababa")
        self.save.configure(disabledforeground="#a3a3a3")
        self.save.configure(foreground="#000000")
        self.save.configure(highlightbackground="#d9d9d9")
        self.save.configure(highlightcolor="black")
        self.save.configure(pady="0")
        self.save.configure(relief=FLAT)
        self.save.configure(text="Save")
        self.save.configure(command=saveFunction)

        self.BranchButton = Button(self.notebook_t0)
        self.BranchButton.place(relx=0.25, rely=0.85, height=55, width=149)
        self.BranchButton.configure(activebackground="#bababa")
        self.BranchButton.configure(activeforeground="#000000")
        self.BranchButton.configure(background="#bababa")
        self.BranchButton.configure(disabledforeground="#a3a3a3")
        self.BranchButton.configure(foreground="#000000")
        self.BranchButton.configure(highlightbackground="#d9d9d9")
        self.BranchButton.configure(highlightcolor="black")
        self.BranchButton.configure(pady="0")
        self.BranchButton.configure(relief=FLAT)
        self.BranchButton.configure(text='''New Branch''')
        self.BranchButton.configure(width=77)
        self.BranchButton.configure(command=lambda: nbPopup())

        self.newset = Button(self.notebook_t0)
        self.newset.place(relx=0.0, rely=0.85, height=55, width=149)
        self.newset.configure(activebackground="#bababa")
        self.newset.configure(activeforeground="#000000")
        self.newset.configure(background="#bababa")
        self.newset.configure(disabledforeground="#a3a3a3")
        self.newset.configure(foreground="#000000")
        self.newset.configure(highlightbackground="#d9d9d9")
        self.newset.configure(highlightcolor="black")
        self.newset.configure(pady="0")
        self.newset.configure(relief=FLAT)
        self.newset.configure(text='''New Set''')
        self.newset.configure(command=lambda: nbsPopup())

        self.delete = Button(self.notebook_t0)
        self.delete.place(relx=0.75, rely=0.85, height=55, width=155)
        self.delete.configure(activebackground="#bababa")
        self.delete.configure(activeforeground="#000000")
        self.delete.configure(background="#bababa")
        self.delete.configure(disabledforeground="#a3a3a3")
        self.delete.configure(foreground="#000000")
        self.delete.configure(highlightbackground="#d9d9d9")
        self.delete.configure(highlightcolor="black")
        self.delete.configure(pady="0")
        self.delete.configure(relief=FLAT)
        self.delete.configure(text='''Delete''')
        self.delete.configure(command=lambda: deletePopup())

        self.editbutton = Button(self.notebook_t0)
        self.editbutton.place(relx=0.5, rely=0.85, height=55, width=149)
        self.editbutton.configure(activebackground="#bababa")
        self.editbutton.configure(activeforeground="#000000")
        self.editbutton.configure(background="#bababa")
        self.editbutton.configure(disabledforeground="#a3a3a3")
        self.editbutton.configure(foreground="#000000")
        self.editbutton.configure(highlightbackground="#d9d9d9")
        self.editbutton.configure(highlightcolor="black")
        self.editbutton.configure(pady="0")
        self.editbutton.configure(relief=FLAT)
        self.editbutton.configure(text='''Edit''')
        self.editbutton.configure(command=editPopup)

        def send(): #on click
            global v
            global atxtbox
            cmdString = "python "+opFiles.get("jobhandler")
            nonEmpty = False
            for x in range(0,len(v)):
                x=x+1
                curTab = v[x]
                for z in curTab:
                    curBox = atxtbox[z]
                    txt = curBox.get()
                    print("Val -> "+z+": "+txt)
                    if txt == "":
                        cmdString = cmdString+'-'+z+' " " '
                    else:
                        nonEmpty = True
                        cmdString = cmdString+'-'+z+' "'+txt+'" '
            cmdString = cmdString+'-outputFile "'+filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("INI file","*.ini"), ("all files","*.*")))
            #print(cmdString)
            if nonEmpty == True:
                lgt = len(cmdString)
                if lgt > 4:
                    if cmdString[(lgt-4):lgt] != ".ini":
                        cmdString = cmdString+".ini"
                os.system(cmdString)
                return"Sent to Job File Handler."
            else:
                print("All values were empty.")



        """
        self.Save = Button(self.notebook_t1)
        self.Save.place(relx=0.0, rely=0.0, height=25, relwidth=0.333)
        self.Save.configure(activebackground="#bababa")
        self.Save.configure(background="#bababa")
        self.Save.configure(disabledforeground="#bababa")
        self.Save.configure(foreground="#000000")
        self.Save.configure(highlightbackground="#000000")
        self.Save.configure(highlightcolor="#000000")
        self.Save.configure(pady="0")
        self.Save.configure(relief=FLAT)
        self.Save.configure(text='''Export''')
        self.Save.bind("<Button-1>", send)
        """

        self.Open1 = Button(self.notebook_t1)
        self.Open1.place(relx=0, rely=0.0, height=25, relwidth=0.5)
        self.Open1.configure(activebackground="#bababa")
        self.Open1.configure(background="#bababa")
        self.Open1.configure(disabledforeground="#bababa")
        self.Open1.configure(foreground="#000000")
        self.Open1.configure(highlightbackground="#000000")
        self.Open1.configure(highlightcolor="#000000")
        self.Open1.configure(pady="0")
        self.Open1.configure(relief=FLAT)
        self.Open1.configure(text='''Open''')
        self.Open1.configure(command=openJobStart)
        #self.Open1.bind("<Button-1>", openJobStart)

        self.Save2 = Button(self.notebook_t1)
        self.Save2.place(relx=0.5, rely=0.0, height=25, relwidth=0.5)
        self.Save2.configure(activebackground="#bababa")
        self.Save2.configure(background="#bababa")
        self.Save2.configure(disabledforeground="#bababa")
        self.Save2.configure(foreground="#000000")
        self.Save2.configure(highlightbackground="#000000")
        self.Save2.configure(highlightcolor="#000000")
        self.Save2.configure(pady="0")
        self.Save2.configure(relief=FLAT)
        self.Save2.configure(text='''Save''')
        self.Save2.configure(command=send)
        #self.Save2.bind("<Button-1>", send)
        global preset
        numMade = 0
        for z in range(0,len(v)):
            global atxtbox
            #print("Z -> "+str(z))
            z = z+1
            curTab = v[z]
            for key in curTab:
                specY = z * 25
                self.TLabel1 = ttk.Label(self.notebook_t1)
                self.TLabel1.place(relx=0.0, y=specY, height=25, width=200)
                self.TLabel1.configure(background="#d9d9d9")
                self.TLabel1.configure(foreground="#000000")
                self.TLabel1.configure(font="TkDefaultFont")
                self.TLabel1.configure(relief=FLAT)
                self.TLabel1.configure(text=key)
                self.TLabel1.configure(wraplength="200")
                self.TEntry1 = ttk.Entry(self.notebook_t1)
                self.TEntry1.place(relx=0.4, y=specY, height=25, relwidth=0.6)
                self.TEntry1.configure(takefocus="")
                self.TEntry1.configure(width=405)
                self.TEntry1.configure(cursor="ibeam")
                self.TEntry1.configure(textvariable=curTab[key])
                atxtbox[key] = self.TEntry1
                numMade = numMade + 1
                specY = specY + 25
class AutoScroll(object): # The following code is added to facilitate the Scrolled widgets you specified.
    '''Configure the scrollbars for a widget.'''

    def __init__(self, master):
        #  Rozen. Added the try-except clauses so that this class
        #  could be used for scrolled entry widget for which vertical
        #  scrolling is not supported. 5/7/14.
        try:
            vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
        except:
            pass
        hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)

        #self.configure(yscrollcommand=_autoscroll(vsb),
        #    xscrollcommand=_autoscroll(hsb))
        try:
            self.configure(yscrollcommand=self._autoscroll(vsb))
        except:
            pass
        self.configure(xscrollcommand=self._autoscroll(hsb))

        self.grid(column=0, row=0, sticky='nsew')
        try:
            vsb.grid(column=1, row=0, sticky='ns')
        except:
            pass
        hsb.grid(column=0, row=1, sticky='ew')

        master.grid_columnconfigure(0, weight=1)
        master.grid_rowconfigure(0, weight=1)

        # Copy geometry methods of master  (taken from ScrolledText.py)
        if py3:
            methods = Pack.__dict__.keys() | Grid.__dict__.keys() \
                  | Place.__dict__.keys()
        else:
            methods = Pack.__dict__.keys() + Grid.__dict__.keys() \
                  + Place.__dict__.keys()

        for meth in methods:
            if meth[0] != '_' and meth not in ('config', 'configure'):
                setattr(self, meth, getattr(master, meth))

    @staticmethod
    def _autoscroll(sbar):
        '''Hide and show scrollbar as needed.'''
        def wrapped(first, last):
            first, last = float(first), float(last)
            if first <= 0 and last >= 1:
                sbar.grid_remove()
            else:
                sbar.grid()
            sbar.set(first, last)
        return wrapped

    def __str__(self):
        return str(self.master)
def _create_container(func):
    '''Creates a ttk Frame with a given master, and use this new frame to
    place the scrollbars and the widget.'''
    def wrapped(cls, master, **kw):
        container = ttk.Frame(master)
        return func(cls, container, **kw)
    return wrapped
class ScrolledText(AutoScroll, Text):
    '''A standard Tkinter Text widget with scrollbars that will
    automatically show/hide as needed.'''
    @_create_container
    def __init__(self, master, **kw):
        Text.__init__(self, master, **kw)
        AutoScroll.__init__(self, master)
if __name__ == '__main__':
    vp_start_gui()
