-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes
local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require

local function print(...) _G.print(...) end

local wstr=require("wetgenes.string")


module("bulb.icles")

function bake(state,icles)
	local icles=icles or {}

	local cake=state.cake
	local game=cake.game
	local gl=state.gl
	
	local classes={	}
	
	icles.feathers={}
	function icles.feathers.start(t)
		icles.feathers.active=true
		icles.feathers.count=0
	end
	function icles.feathers.stop()
		icles.feathers.active=false
	end
	function icles.feathers.update()
		if not icles.feathers.active then return end
		
		if icles.feathers.count < 100 then
		
--			if math.random(1,100)>80 then
				classes.feather.create({
					px=math.random(0,320),
					py=-100,
					vx=math.random(-100,100)/100,
					vy=1+(math.random(0,100)/100),
					id=math.random(1,6),
					})
--			end
			
		end
	end
	
	classes.feather={}
	function classes.feather.create(t)
		local v={}		
		icles.tab[ v ]=v
		icles.tab[ #icles.tab+1 ]=v
		v.class=classes.feather
		v.px=t.px or 0
		v.py=t.py or 0
		v.vx=t.vx or 0
		v.vy=t.vy or 0
		v.rz=t.rz or 0
		v.id=t.id or 1
		icles.feathers.count=icles.feathers.count+1
		return v
	end
	function classes.feather.destroy(v)
		icles.tab[v]=nil
		icles.feathers.count=icles.feathers.count-1
	end
	
	function classes.feather.update(v)
		v.px=v.px+v.vx
		v.py=v.py+v.vy
		v.rz=v.rz+v.vx*4
		
		if v.py> 480+100 then
			v.class.destroy(v)
		end
	end
	function classes.feather.draw(v)
		gl.Color(1/32,1/32,1/32,0)
		local bulbs=cake.sheets.get("bulbs")
		bulbs:draw(v.id,v.px,v.py,v.rz,200,200)
	end
	
	function icles.loads()
	end
	
	function icles.setup()
		
		icles.tab={}
		
	end
	
	function icles.update()
	
		icles.feathers.update()
	
		local i=1
		while i<#icles.tab do
			v=icles.tab[i]
			v.class.update(v)
			if not icles.tab[v] then -- flaged as dead
				table.remove(icles.tab,i) -- everything shifts down 1
			else -- next
				i=i+1
			end
		end
		
	end

	function icles.draw()
		
		for i,v in ipairs(icles.tab) do
			v.class.draw(v)
		end

		gl.Color(1,1,1,1)	
	end
	
	return icles
end
