@name Bank Vault DoorCore
@persist Doors:table
@inputs DoorOverride
Bank=gTable("sBank")

#gtable sBank
    #array Safelist
    #table GlobalData
        #table Vaults
            #table VaultObject
                # 1 - number Owned
                # 2 - array Owners
                    # string Owner
                # 3 - entity Door
    #string SteamID32 - table UserObject
        #number Timeleft
        #array Owned

runOnChat(1)
interval(1000)

if (chatClk(owner()) & owner():lastSaid():sub(1,1)=="-") {
    hideChat(1)
    local Command=owner():lastSaid():sub(2):explode(" ")
    switch(Command[1,string]) {  
        case "reset*",
            Bank:clear()
            Bank["Safelist",array]=array()
            Bank["GlobalData",table]=table()
            Bank["GlobalData",table]["Vaults",table]=table()
            Bank["Userlist",array]=array()
            Bank["Username",table]=table()
            printColor(vec(255,255,0),"[sBank] ",vec(255,0,0),"All bank data wiped.")
        break
              
        case "addsafe",
            print("Adding safe")
            #if (owner():aimEntity():wirelink():hasInput("Fade")) {
                Command:removeString(1)
                Safename=Command:concat(" ")
                local OK=1
                for (I=1, Bank["Safelist",array]:count()) {
                    local ID=Bank["Safelist",array][I,string]
                    local V=Bank["GlobalData",table]["Vaults",table][ID,table]
                    #print(ID)
                    #print(V[1,number],V[2,array],V[3,entity])
                    if (V[3,entity]==owner():aimEntity()) {
                        OK=0
                    }
                }
                if (OK) {
                    printColor(vec(255,255,0),"[sBank] ",vec(255),"Safe ",vec(0,255,0),Safename,vec(255)," has been added.")
                    Bank["GlobalData",table]["Vaults",table][Safename,table]=table(0,array(owner():steamID()),owner():aimEntity())
                    Bank["Safelist",array]:pushString(Safename)
                } else {
                    printColor(vec(255,255,0),"[sBank] ",vec(255),"This door is already a safe.")
                }
            #}
        break
    }
}

if (clk()) {
    foreach(I,V:string=Bank["Safelist",array]) {
        local ID=V
        local Safe=Bank["GlobalData",table]["Vaults",table][ID,table]
        local Owned=Safe[1,number]
        local Owners=Safe[2,array]
        local Entity=Safe[3,entity]
        findByClass("player")
        local Closest=findClosest(Entity:pos())
        local Open=0
        if (Closest:pos():distance(Entity:pos())<80 & Closest:aimEntity()==Entity & Closest:keyUse()) {
            foreach(I,V:string=Owners) {
                #print(Closest:steamID(),V)
                if (Closest:steamID()==V) {
                    Open=1
                }
            }
        }
        local WL=Entity:wirelink()
        WL["Fade",number]=Open | DoorOverride
    }
}
