-- SmokeUnit.lh -- Process unit smoke when damaged

#include "SFXtype.lh"
#include "EXPtype.lh"

-- Figure out how many smoking pieces are defined

if __this.SMOKEPIECE4 ~= nil then
    __this.NUM_SMOKE_PIECES = 4
elseif __this.SMOKEPIECE3 ~= nil then
    __this.NUM_SMOKE_PIECES = 3
elseif __this.SMOKEPIECE2 ~= nil then
    __this.NUM_SMOKE_PIECES = 2
else
    __this.NUM_SMOKE_PIECES = 1
    if __this.SMOKEPIECE1 == nil then
        __this.SMOKEPIECE1 = __this.SMOKEPIECE
    end
end

__this.SmokeUnit = function (this)
    local healthpercent
    local sleeptime
    local smoketype
    local random = math.random

    -- Wait until the unit is actually built
    while this:get(BUILD_PERCENT_LEFT) > 0 do
        sleep(0.4)
    end

    -- Smoke loop
    while true do
        -- How is the unit doing?
        healthpercent = this:get( HEALTH )

        if healthpercent < 66 then
            -- Emit a puff of smoke

            smoketype = SFXTYPE_BLACKSMOKE

            if random( 1, 66 ) < healthpercent then
                smoketype = SFXTYPE_WHITESMOKE
            end

             -- Figure out which piece the smoke will emit from, and spit it out

            if this.NUM_SMOKE_PIECES == 1 then
                this:emit_sfx( smoketype, this.SMOKEPIECE1 )
            else
                local choice = random( 1, this.NUM_SMOKE_PIECES )

                if choice == 1 then
                    this:emit_sfx( smoketype, this.SMOKEPIECE1 )
                elseif choice == 2 then
                    this:emit_sfx( smoketype, this.SMOKEPIECE2 )
                elseif this.NUM_SMOKE_PIECES >= 3 then
                    if choice == 3 then
                        this:emit_sfx( smoketype, this.SMOKEPIECE3 )
                        if this.NUM_SMOKE_PIECES >= 4 and choice == 4 then
                            this:emit_sfx( smoketype, this.SMOKEPIECE4 )
                        end
                    end
                end
            end
        end

        -- Delay between puffs

        sleeptime = healthpercent * 0.05
        if sleeptime < 0.2 then
            sleeptime = 0.2    -- Fastest rate is five times per second
        end

        sleep( sleeptime )
    end
end

