@name Anti-Air Cannon
@persist [Props Settings]:table Color:vector Can:entity [Owner Entity]:entity
@persist [Lua_Explosion]:string Lua:entity
@model models/hunter/plates/plate1x1.mdl

interval(100)
runOnChat(1)

if (first()) {
    Owner=owner()
    Entity=entity()
    
    Entity:setAlpha(0)
    Entity:propNotSolid(1)
    
    Settings["Enabled",number]=1
    Settings["MaxActive",number]=300
    Settings["DetTime",number]=30
    Settings["SpinUp",number]=3
    Settings["Speed",number]=10e30 # 10e30
    Settings["Explosive",number]=1
    Settings["Mass",number]=50000
    Settings["Targets",array]=array()
    Settings["Precision",number]=0
    Settings["LaunchSpeed",number]=10
    Settings["Dist",number]=200
    Settings["ExplosiveScalar",number]=1
    #Settings["Model",string]="models/props_c17/statue_horse.mdl"
    Settings["Model",string]="models/cheeze/pcb2/pcb1.mdl"
    #Settings["Model",string]="models/props_c17/furnitureStove001a.mdl"
    
    Props["Active",number]=0
    Props["Made",number]=0
    
    function number makeCan() {
        if (!propCanCreate()) {return 0}
        
        Props["Made",number]=Props["Made",number]+1
        # Can=propSpawn("models/props_junk/PopCan01a.mdl",1)
        # Can=propSpawn("models/props_c17/doll01.mdl",1)
        #Can=propSpawn("models/weapons/w_models/w_sapper.mdl",1)
        #Can=propSpawn("models/props/cs_assault/Money.mdl",1)
        # Can=propSpawn("models/weapons/w_snip_awp.mdl",1)
        #Can=propSpawn("models/Items/HealthKit.mdl",1)
        Can=propSpawn(Settings["Model",string],1)
        #Can=propSpawn("models/props_c17/Lockers001a.mdl",1)
        # Can=propSpawn("models/weapons/w_knife_t.mdl",1)
        
        Can:setPos(Entity:toWorld(vec(0,0,25)))
        Can:setAng(Entity:angles())
        #Can:setMaterial("debug/debugdrawflat")
        
        local Col=hsv2rgb(((Props["Made",number]%Settings["MaxActive",number])/Settings["MaxActive",number])*360,1,1)
        Can:setColor(Col)
        #Can:setTrails(16,1,5,"trails/laser",Col,255)
        Can:setMass(Settings["Mass",number])
        Can:soundPlay(4,0,"weapons/ar2/ar2_reload_push.wav")
        #Can:parentTo(Entity())
        
        Color=Col
        
        return 1
    }
    
    function number spawn(E:entity) {
        if (!Can | Props["Active",number]>=Settings["MaxActive",number]) {return 0}
        #Can:deparent()
        Can:soundPlay(3,0,"weapons/ar2/ar2_altfire.wav")
        soundPitch(3,200)
        Props["Active",number]=Props["Active",number]+1
        Props["Ent_"+Can:id(),table]=
            table(
                "Ent"=Can,
                "Target"=E,
                "LaunchTime"=curtime()+Settings["SpinUp",number],
                "DetTime"=curtime()+Settings["DetTime",number]
            )
        Can:propGravity(0)
        Can:propFreeze(0)
        Can:applyForce(
            (Entity:angles():up()+vec(randint(-10,10)/100,randint(-10,10)/100,0))
                *500*Settings["Mass",number]
        )
        Can=noentity()
    }
    
    makeCan()
    
    Color=vec(0,255,0)
    
    local OffsetY=5
    holoCreate(1)
    holoModel(1,"models/Mechanics/wheels/wheel_extruded_48.mdl")
    holoParent(1,Entity)
    holoPos(1,Entity:toWorld(vec(0,0,6+OffsetY)))
    
    holoCreate(2)
    holoModel(2,"models/mechanics/wheels/wheel_smooth_72w.mdl")
    holoParent(2,Entity)
    holoPos(2,Entity:toWorld(vec(0,0,1+OffsetY)))
    holoScale(2,vec(0.7,0.7,0.6))
    
    holoCreate(3)
    holoModel(3,"models/XQM/Rails/gumball_1.mdl")
    holoParent(3,Entity)
    holoPos(3,Entity:toWorld(vec(0,0,11+OffsetY)))
    holoScale(3,vec(0.2))
    holoMaterial(3,"debug/debugdrawflat")
    
    holoCreate(4)
    holoModel(4,"models/maxofs2d/hover_rings.mdl")
    holoParent(4,Entity)
    holoPos(4,Entity:toWorld(vec(0,0,11+OffsetY)))
    holoScale(4,vec(0.65))
    
    holoCreate(5)
    holoModel(5,"models/mechanics/wheels/wheel_rounded_36s.mdl")
    holoParent(5,Entity)
    holoPos(5,Entity:toWorld(vec(0,0,-5+OffsetY)))
    holoScale(5,vec(1.4,1.4,1))
    # lightCreate(1)
    # lightPos(1,holoEntity(3):pos())
    # lightParent(1,holoEntity(3))
    
    holoEntity(1):soundPlay(1,0,"mvm/mvm_tele_activate.wav")
    holoEntity(1):soundPlay(0,0,"ambient/machines/thumper_amb.wav")
    soundPitch(0,120)
    soundVolume(0,20)
    
    timer("LaunchLoop",2000)
    
    #########################
    # Lua Strings - CT Only #
    #########################
    findByClass("lua_run")
    Lua=find()
    
    Lua_Explosion="
        local Pos=Vector(%d,%d,%d)
        for i=1,1 do ParticleEffect(\"grenade_final\",Pos,Angle(0, 0, 0),nil) end
        util.ScreenShake(Pos,500,500,2,500)
        
        local Explode=ents.Create('env_explosion')
	       Explode:SetPos(Pos)
	       Explode:Spawn()
	       Explode:SetKeyValue('iMagnitude','100')
	       Explode:SetKeyValue('spawnflags','64')
	       Explode:Fire('Explode',0,0 )
    "
    
    function lua_Run(S:string) {
        # luaRun(S)
    }
    
    function explode(V:vector) {
        V+=vec(0,0,30)
        local String=format(Lua_Explosion,V:x(),V:y(),V:z())
        lua_Run(String)
    }
}

holoAng(2,Entity:toWorld(ang(0,curtime()*16,0)))
holoAng(1,Entity:toWorld(ang(0,-curtime()*16,0)))

if (changed(Color)) {
    # lightColor(1,Color*0.06)
    holoColor(3,Color)
}

if (!Can) {makeCan()}

local Time=curtime()

foreach(I,V:table=Props) {
    local Ent=V["Ent",entity]
    local Target=V["Target",entity]
    local TargetPos=V["TargetPos",vector] ?: Target:pos()
    local Launched=V["LaunchTime",number]<Time
    
    if(Launched) {
        Ent:applyForce(-Ent:vel()*Ent:mass()*Settings["Precision",number])
        Ent:applyForce((Ent:pos()-TargetPos):toAngle():forward()*-Settings["Speed",number]*Settings["Mass",number])
        Ent:setAng(ang(randint(360),randint(360),randint(360)))
        if (!V["Moving",number]) {
            Ent:soundPlay("Move",0,"weapons/airboat/airboat_gun_energy1.wav")
            Props[I,table]["Moving",number]=1
        }
    }
    
    if(!V["TargetPos",vector] & Target:isPlayer() & !Target:isAlive()) {
        Props[I,table]["TargetPos",vector]=Target:pos()
    }
    
    local Dist=Ent:pos():distance(TargetPos)
    if (Launched & (V["DetTime",number]<Time | (Settings["Explosive",number] & Dist<Settings["Dist",number]))) {
        holoCreate(7,Ent:pos(),vec(),ang())
        holoAlpha(7,0)
        holoEntity(7):soundPlay("Exp",0,"Explo.ww2bomb") #holoEntity(7):soundPlay("Explode",0,"ambient/explosions/explode_3.wav")
        explode(Ent:pos())
        Ent:propDelete()
        Props:removeTable(I)
        Props["Active",number]=Props["Active",number]-1
        #concmd("ulx ungod \""+Target:name()+"\"")
    }
}

if (Owner:isAlive() & (chatClk(Owner) & Owner:lastSaid():sub(1,1)==".")) {
    hideChat(1)
    local Command=Owner:lastSaid():sub(2):explode(" ")
    if (Command[1,string]=="fire") {
        local Ply=findPlayerByName(Command[2,string]:lower())
        local Number=Command[3,string]:lower():toNumber()
        if (!Ply) {
            printColor(vec(0,255,255),"[AA] ",vec(255),"Could not find/found 2+ of ",vec(255,0,0),Command[2,string],vec(255),".")
        }
        if (Number<=0) {
            printColor(vec(0,255,255),"[AA] ",vec(255,0,0),Command[3,string],vec(255)," is not a valid number.")
        }
        if (Ply & Number>0) {
            for(I=1,Number) {Settings["Targets",array]:pushEntity(Ply)}
            printColor(vec(0,255,255),"[AA] ",vec(0,255,0),Ply:name(),vec(255)," was targeted ",vec(0,255,0),Number,vec(255)," times.")
        }
    }
    
    if (Command[1,string]=="fireadmins") {
        foreach(I,V:entity=players()) {
            if (V:isAdmin()) {Settings["Targets",array]:pushEntity(V)}
        }
    }
}

if (clk("LaunchLoop")) {
    timer("LaunchLoop",Settings["LaunchSpeed",number])
    if (Can & Settings["Targets",array]:count()>0) {
        while(1) {
            local Target=Settings["Targets",array]:popEntity()
            if (!Target:isPlayer() | Target:isAlive()) {
                spawn(Target)
                break
            }
        }
    }
}
