@name Countdown Timer

@inputs 
@outputs Idx T:entity Time [Min Max]:vector Last:entity
@persist EGP:wirelink E:entity
@trigger 

if( first() )
{
    E = entity():isWeldedTo() ?: entity()
    O = owner()
    
    findIncludePlayerProps(O)
    #findByClass("gmod_wire_egp_emitter")
    findByClass("gmod_wire_egp")
    EGPent = findClosest(E:pos())
    EGP = EGPent:wirelink()
    
    function number getID( N )
    {
        return EGP:egpNumObjects() + N
    }
    
    EGP:egpClear()
    
    EGP:egpRoundedBox( getID(1), vec2(256,256), vec2(512,512) )
    EGP:egpColor( getID(0), hsv2rgb( 200, 1, 1 ) )
    EGP:egpAlpha( getID(0), 150 )
    
    EGP:egpTextLayout( getID(1), "name", vec2(), vec2(512,512) )
    EGP:egpAlign( getID(0), 1, 1 )
    EGP:egpFont( getID(0), "", 40 )
    EGP:egpColor( getID(0), vec() )
    
    Time = 40
    
    Bx = E:aabbSize()
    
    V1 = E:toWorld(vec(Bx[1]/2,Bx[2]/2,0))
    V2 = E:toWorld(vec(-Bx[1]/2,-Bx[2]/2,Bx[1]))
    
    Min = vec( min( V1[1], V2[1] ),
                min( V1[2], V2[2] ),
                min( V1[3], V2[3] )
                )
    Max = vec( max( V1[1], V2[1] ),
                max( V1[2], V2[2] ),
                max( V1[3], V2[3] )
                )
#    holoCreate( 1, mix( V1, V2, 0.5 ), -positive(V1-V2) / 12, E:angles() )
#    holoParent( 1, E )
    
    findClearBlackList()
    findClearWhiteList()
}

interval(50)

if( findCanQuery() )
{
    findByClass("player")
    findClipToBox(Min,Max)
    T = findClosest(E:pos())
}

if( changed(T) )
{
    if( !Time ){ Time = 40 }
    
    if( T )
    {
        Last = T
        EGP:egpSetText( 2, T:name() + "\n\nCOUNTDOWN\n\n"+Time )
        timer("countdown",1000)
    }
    else
    {
        stoptimer("countdown")
    }
}

if( clk("countdown") & Time )
{
    Time = max( 0, Time - 1 )
    if( Time >= 10 )
    {
        E:soundPlay( "count", 0, "@synth/saw.wav", 0.5 )
    }
    else
    {
        soundPurge()
        E:soundPlay( "count", 0, "@buttons/weapon_cant_buy.wav", 0.5 )
    }
    soundPitch("count",Time>=10 ? 200 : 100)
    soundVolume("count",Time>=10 ? 0.1 : 1)
    timer("countdown",1000)
}

if( changed(Time) )
{
    EGP:egpSetText( 2, Last:name() + "\n\nCOUNTDOWN\n\n"+Time )
    if( !Time )
    {
        E:soundPlay("bell",0,"@buttons/bell1.wav")
        if( Last:isValid() )
        {
            EGP:egpSetText( 2, Last:name() + "\n\n IS THE WINNER!" )
            #E:soundPlay("win",5,"@misc/boring_applause_1.wav")
            E:soundPlay("win",5,"@misc/happy_birthday.wav")
            concmd("say \"/advert "+Last:name()+ "  Is the WINNER of the CG Competition\"")
            concmd("rp_tellall "+Last:name()+ "  Is the WINNER of the CG Competition")
        }
        else
        {
            EGP:egpSetText( 2, "THERE IS NO WINNER\nYOU ALL FAIL" )
        }
    }
}
