-- current switches
dofile("scripts/entities/entityInclude.lua")

CURRENTSWITCH_OFF	= 1
CURRENTSWITCH_ON	= 2

bone_orb = 0

function commonInit(me)
	entity_setEntityType(me, ET_NEUTRAL)
	entity_setWidth(me, 64)
	entity_setHeight(me, 64)
	entity_setUpdateCull(me, -1)
	entity_setActivation(me, AT_CLICK, 64, 256)
	entity_initSkeletal(me, "FleshSwitch")
	entity_animate(me, "idle", LOOP_INF)
	bone_orb = entity_getBoneByName(me, "Orb")
end

function postInit(me)
	debugLog("postInit")
	if entity_isFlag(me, CURRENTSWITCH_ON) then
		entity_setState(me, STATE_ON)
	elseif entity_isFlag(me, CURRENTSWITCH_OFF) then
		entity_setState(me, STATE_OFF)
	end	
end

function setGroupState(me, state)
	if entity_getGroupID(me) ~= 0 then
		iter = 0
		ent = getEntityInGroup(entity_getGroupID(me), iter)
		while (ent ~= 0) do
			--debugLog("Looping thru group")
			if not (ent == me) then
				if not entity_isState(ent, state) then
					entity_setState(ent, state)
				end
			end
			iter = iter + 1
			ent = getEntityInGroup(entity_getGroupID(me), iter)
		end
	end
end

function enterState(me, state)
	if entity_isState(me, STATE_ON) then
	
		debugLog("setting on")
		entity_animate(me, "open")
		--entity_setNodeGroupActive(me, 0, true)
		node = getNearestNodeByType(entity_x(me), entity_y(me), PATH_CURRENT)
		if node ~= 0 then
			debugLog("found node, setting")
			node_setActive(node, true)
		else
			debugLog("did not find node")
		end
		entity_setFlag(me, CURRENTSWITCH_ON)
		-- turn other switches off
		setGroupState(me, STATE_OFF)
		--bone_setColor(bone_orb, 0, 1, 0, 0.5)
		--entity_setColor(me, 0, 1, 0, 0)
	elseif entity_isState(me, STATE_OFF) then
		debugLog("setting off")
		entity_animate(me, "close")
		--entity_setNodeGroupActive(me, 0, false)
		node = getNearestNodeByType(entity_x(me), entity_y(me), PATH_CURRENT)
		if node ~= 0 then
			node_setActive(node, false)
		end		
		entity_setFlag(me, CURRENTSWITCH_OFF)
		-- turn other switches on
		setGroupState(me, STATE_ON)
		--bone_setColor(bone_orb, 1, 0, 0, 0.5)
		--entity_setColor(me, 1, 0, 0, 0)
	end
end

function activate(me)
	if entity_isFlag(me, CURRENTSWITCH_OFF) then
		debugLog("setting stateon")
		entity_setState(me, STATE_ON)
	end
end

function songNote(me, note)

end

function update(me)
end
