-----------------------------------------------------------
-- EDIT ENTITY PROPERTIES
-----------------------------------------------------------
local sin = math.sin
local cos = math.cos
local tan = math.tan


function editor.deleteSelected()
	for i,entity in ipairs(selectedEntities) do 
		scene.setDelete(entity)
	end
	lume.clear(selectedEntities)
end

function editor.deleteFromSelectedEntities(ent)
	for i,e in ipairs(selectedEntities) do 
		if e.uid == ent.uid then 
			table.remove(selectedEntities,i)
		end
	end
end

function editor.checkForSimples()
	anySelectedSimple=false
	if hoveredEntity~=nil and hoveredEntity.simple then 
		anySelectedSimple=true 
	end
	for i,entity in ipairs(selectedEntities) do 
		if entity.simple  then 
			anySelectedSimple=true 
		end
	end
	return anySelectedSimple
end

function editor.checkForSemiSimples()
	anySelectedSemiSimple=false
	if hoveredEntity~=nil and (hoveredEntity.simple or (hoveredEntity.light and hoveredEntity.light.enabled and not hoveredEntity.visible)) then 
		anySelectedSemiSimple=true 
	end
	for i,entity in ipairs(selectedEntities) do 
		if entity.simple or (entity.light and entity.light.enabled and not entity.visible) then 
			anySelectedSemiSimple=true 
		end
	end
	return anySelectedSemiSimple
end


function editor.updateEntityProperties()
	if  instancePanel.open then 
		editor.saveAllEntityProperties()
	end 	
end

function plane(entity,pos)
	pos = getFloorCoords 				(entity)
	entity:setPosition 					(entity.x ,entity.y,pos and -pos.z+entity.offsetz or entity.z)
	pos = getFrontCoords 				(entity)
	entity:setPosition 					(pos and -pos.x+entity.offsetx or entity.x ,entity.y,entity.z)
end

function editor.updateEntityTransform(entity)
	local panel = animationPanel

	if (entity.selected or (panel.open and entity==panel.transformer)) and view == currentRoom  then

		local pos
		local ylock 	= false
		local planing  	= (entity.simple and pathsPanel.open and (pathsPanel.mode == "floors" or pathsPanel.mode == "ramps"))
		local ramping  	= (entity.simple and pathsPanel.open and pathsPanel.mode == "ramps" and #selectedEntities==1)
		local flooring  = (entity.simple and pathsPanel.open and pathsPanel.mode == "floors")
		if flooring and #selectedEntities ~= #pathsPanel.points then 
			ylock = true
		end

		local overhead 	= (cam.overhead or ylock)

		entity:updateTransform()

		------------------------ SORT OBJECT 	---------------------------
		if multiTool.sorting or flooring then 	
			-- 	local mult 		= room.zbounds.range*(shiftDown and 0.5 or 1)
			-- 	local diff = lerp(0,1, (math.abs(multiTool.start.y-mouse.y)/(screenHeight/2)) ) * lume.sign(multiTool.start.y-mouse.y)
		end
	end
end

function applyTransform(e,p,o,s)
	e = e or {}
	e.transform = e.transform and e.transform:identity() or mat4()
	e.transform:scale(e.transform,s or e.scale or vec3(1))
	e.transform:mul(e.transform,mat4.from_quaternion(quat(0,1,0,-1)))
	e.transform:translate(e.transform,p or e.position or vec3(0))
	return e.transform
end



function previewTransform(e)
	if multiTool.dragging then 
		e.nextPosition = e.position+multiTool.translation
		e.transform = mat4()
		e.transform = e.transform*mat4.from_quaternion(e.orientation)
		e.transform:translate(e.transform,e.nextPosition)
	elseif multiTool.rotating then 
		e.transform = mat4()
		e.nextOrientation = (e.orientation) * quat.rotate(multiTool.angle,multiTool.axis)
		e.transform = e.transform*mat4.from_quaternion(e.nextOrientation)
		e.transform:translate(e.transform,multiTool.position-(multiTool.position-e.position):rotate(-multiTool.angle,multiTool.axis))
	else 
		e.transform = mat4()
		e.transform:scale(e.transform,e.scale)
		e.transform = e.transform*mat4.from_quaternion(e.orientation)
		e.transform:translate(e.transform,e.position)
	end

	for m,model in ipairs(e.models) do
		model.matrix = scene.getMatrix(model)
	end
	return e.transform
end

function editor.resetTransform(e)
	if e then 

	else
		for i,e in ipairs(selectedEntities) do 
			e:setScale(1,1,1)
			e:setPosition(0,0,0)
			e:setRotation(2*pi,vec3(1,0,0))
		end
	end
end

function editor.applyTransforms()
	for e,entity in ipairs(selectedEntities) do
		entity:applyTransform()
	end
	if animationPanel.open then 
		if animationPanel.transformer.position and animationPanel.instance.orientation  then 
			editor.applyFrameTransform(animationPanel)
		end
	end
	multiTool.translation = vec3(0)
	multiTool.screenRotate = false
end

function editor.shouldPlane(entity)
	return math.abs(entity.y-zcam.pos.y)>200
end

function editor.transformEntities(view)
	--trace("anySelectedSimple",anySelectedSimple)
	
	selectAll 				= false
	preTransform 			= false
	editor.wasTransforming 	= editor.transforming
	editor.transforming 				= (multiTool.dragging or multiTool.rotating or multiTool.scaling or multiTool.sorting)
	editor.transformTime=editor.transforming and editor.transformTime+1 or 0

	local startedTransform = (editor.transforming and not editor.wasTransforming)
	multiTool.hovered	= false


	local altDepth = altDown or (selectedEntities[1] and selectedEntities[1].mode and selectedEntities[1].mode=="floors")
	local showArcs 	=  (not pathsPanel.open or pathsPanel.mode=="paths") and (not (cmdDown and multiTool.dragging)) and (not editor.checkForSimples() or #selectedEntities>1)

	if animationPanel.open and animationPanel.l.type=="model" then 
		showArcs = false
	end


	if startedTransform then 
		--editor.storeMultiToolStart()
	end

	if animationPanel.open and animationPanel.transformer and animationPanel.transformer.enabled then 
		lume.clear(selectedEntities)
		selectedEntities[1] = animationPanel.transformer
		animationPanel.transformer.selected = true
		if drawingPanel.tool ~= "move" or animationPanel.selection.mesh then 
			return
		end
	end


	if #selectedEntities>0 and stageHovered and (editState == "Normal" or editState=="Transforming") and not (lkeyboard.isDown("space") or (keyDown("left") or keyDown("right")) ) then 


		local mul 	= {x=0,y=0,rx=0,ry=0,r=0,s=0,z=0}

		for i,entity in lume.ripairs(selectedEntities) do
			if entity.x then 
				if entity.IsEntity then 
					scene.updateEntityVars(entity)
					scene.updateEntityBounds(entity)
				end

				--if not multiTool.dragging then 
					mul.x = mul.x + entity.x
					mul.y = mul.y + entity.y
					mul.z = mul.z + entity.z
				--end
			end
		end
		

		multiTool.position = (multiTool.dragging and editor.wasTransforming) and multiTool.position or  vec3(
			   mul.x/#selectedEntities
			,  mul.y/#selectedEntities
			,  mul.z/#selectedEntities
		)


		--multiTool.transform=(not altDown and #selectedEntities==1) and selectedEntities[1].transform:clone() or 

		local screenAxis = quat.from_direction(multiTool.position-zcam.pos,vec3.perpendicular(multiTool.position-zcam.pos))
		multiTool.screenAxis = screenAxis 
		
		multiTool.ori = (not altDepth or #selectedEntities>1) and (cmdDown and quat(0,0.001,0,1) or screenAxis) or selectedEntities[1].orientation:clone() 


		multiTool.transform = (not cmdDown and #selectedEntities==1) 
			and (selectedEntities[1].transform or selectedEntities[1]:updateTransform()):clone()
			or mat4():translate(mat4(),multiTool.position+(multiTool.translation or vec3(0,0,0)))


			trace("project multiTool",multiTool.position)
		local projected = camera.project(multiTool.position)

		if projected then 
			mul.x,mul.y,mul.z = projected.x,projected.y,projected.z

			multiTool.screen 	= mul
			if startedTransform then 
				multiTool.diff 	= {x=mouse.x-multiTool.screen.x,y=mouse.y-multiTool.screen.y}
			end
		end

--		multiTool.ray 	= getCursorRay(mouse.x-multiTool.diff.x,mouse.y-multiTool.diff.y)

		if multiTool.dragging then 
			multiTool.ray 	= getCursorRay(mouse.x-multiTool.diff.x,mouse.y-multiTool.diff.y)
		end


		if startedTransform then 
		--	multiTool.startAngle = vec3.angle_to()
		end

		local tooling = false
		local iconScale = 1
		local screenRotate = false
		if not cmdDown and keypressed("r") and not animationPanel.open then 
			--selectedEntities[1]:setPosition(0,0,0)
			--selectedEntities[1].orientation = quat(0,0.001,0,1)
			selectedEntities[1]:setScale(1,1,1)
			selectedEntities[1]:setRotation(0.001,vec3(0,0.001,0))
		end

		local items 
		if #selectedEntities==1 and selectedEntities[1].light.enabled then 
			items = {move=multiTool.items.move}
		else
			items = multiTool.items
		end

		for k,item in pairs(items) do 
			local dist = item.d
			local enabled =true
			local rotate= item.name:sub(1,6) == "rotate"
			local axis = item.name:sub(7,7)


			if altDepth then 
				if k=="move" then 
					--v = multiTool.items.depth
				end 
				if k=="depth" then 
					enabled=false
				end
			elseif cmdDown then

			else
				if rotate then 
					if axis == "Z" then 
						screenRotate=true
					else 
						enabled=false
					end
				end
			end

			if altDepth and cmdDown then 
				enabled=false
			end

			if enabled  then 	

				item.x 	= 	mul.x	+	dist 	*	iconScale 	*	math.sin(item.a) *game.resolution
				item.y 	= 	mul.y	+	dist 	*	iconScale 	*	math.cos(item.a) *game.resolution

				if #selectedEntities==1 and item.name == "moved" and camera.facingDown(cam)  then 

				elseif pathsPanel.open and pathsPanel.mode=="floors" and ( item.name == "depthX") then
				    --do
				else
					local inCircle = (math.dist(item.x,item.y,mouse.x,mouse.y)<item.r*iconScale)
					if rotate and showArcs then 
						item.model.parent = multiTool
						item.model.matrix = scene.getMatrix(item.model)
						if screenRotate then 
							item.hovered = inCircle 
						else 
							trace("hey")
							local sected = testCursorModel(item.model,item.model.parent,true)
							trace(sected)
							item.hovered = (sected and not multiTool.items.move.hovered)
						end
						item.model.brightness = editor.transforming and item.model.brightness or (item.hovered and 1 or 0.7)
						if item.hovered and not multiTool.rotating then 
							
							multiTool.axis = -(mat4.from_quaternion(multiTool.ori))*item.plane
							local coords  = getPlaneCoords(multiTool.position,multiTool.axis)
							local v1 = coords - multiTool.position
							if screenRotate then 
								local az = vec3.normalize(zcam.pos - multiTool.position)
								local ax = vec3.rotate(az, -pi/2, vec3.unit_x)
								multiTool.axis = axis=="Z" and az or (axis=="X" and ax or (axis=="Y" and vec3.cross(az, zcam.lookDirection)))
								multiTool.startAngle = editor.getToolAngle()
							else
								multiTool.startAngle = math.angle(0,0,vec3.dot(multiTool.ori*item.plane1,v1),vec3.dot(multiTool.ori*item.plane2,v1))
							end
							--local ptr = newModel()
							--ptr.transform:translate(mat4(),multiTool.position+multiTool.axis*47)
							--table.insert(currentRoom.room.models,ptr)
						end
					else
						item.hovered 		= inCircle
					end

					preTransform 	= item.hovered and true or preTransform
					if item.hovered and not mouse.down.L then tooling = true end

					if 		item.hovered  then
						multiTool.name= editor.transforming and multiTool.name or item.name
						multiTool.hovered = true
						
						mouse.set(function()
							if animationPanel.open then 
								animationPanel.pushUndoState()
							else
								editor.pushUndoState("Start Transform")
							end
							multiTool.mouse = {x=mouse.x,y=mouse.y}
							multiTool.screenRotate = screenRotate
							multiTool.startTransform = multiTool.transform:clone()
							multiTool.startOri = multiTool.ori:clone()
							multiTool.current = item
							item.func()  
						end)
					end

					if not animationPanel.playing   then 
						if rotate and (altDepth or cmdDown)     then 
							item.model.brightness = multiTool.current == item  and 1 or item.model.brightness
							item.model.layer=-10
							local scale = vec3.dist2(zcam.pos, multiTool.position)/1000000
							item.model.basetransform = item.model.basetransform or mat4(item.model.transform:clone())
							item.model.transform:scale(item.model.basetransform,vec3((1/scale)^0.4))
							if showArcs then 
								table.insert(editor.toolModels,item.model)
							end
						else
							if editor.checkForSemiSimples() and (#selectedEntities==1 or item.name~="move") then 

							elseif not editor.transforming then 
								local img = getImage(tostring(item.name).."Icon")
								local x,y = item.x/game.resolution,item.y/game.resolution
								gfx.setColor(1,1,1,item.hovered and 1 or 0.9)
								gfx.circle( "fill", x, y, item.r*iconScale, 12 )
								gfx.setLineWidth(2)
								local outline = ((editor.transforming and multiTool.start.name==item.name) or item.hovered) and 0.25 or 1
								gfx.setColor(outline,outline,outline,1)
								gfx.circle( "line", x, y, item.r*iconScale, 32 )
								gfx.setColor(0.2,0.2,0.35,0.99)
								gfx.draw(img,mf(x), mf(y),0,iconScale*0.8,iconScale*0.8,mf(img:getWidth()/2),mf(img:getHeight()/2))
							end
						end
					end
				end
			end
		end
		

		if multiTool.dragging and multiTool.position then 
			trace("ffff")
			if cmdDown and editor.debug.trace_mouse_intersect then 
				trace("intersect" ,inspect(editor.intersect))
			end
			multiTool.new = cmdDown and -editor.lastIntersect or (altDepth and  (
				getFloorCoords(multiTool.position,multiTool.ray) or multiTool.new) or (
				getFrontCoords(multiTool.position,multiTool.ray) or multiTool.new))
			multiTool.translation = multiTool.new-multiTool.position or multiTool.translation or vec3(0)

		elseif multiTool.rotating then

			if multiTool.screenRotate then 
				multiTool.angle = #selectedEntities>1 and -multiTool.angle or multiTool.angle

				if multiTool.name == "rotateZ" then 
					multiTool.startAngle = multiTool.startAngle or multiTool.angle
					multiTool.angle 	= multiTool.startAngle + editor.getToolAngle()

				elseif  multiTool.name == "rotateX" then 

					multiTool.angle 	= -(mouse.x - multiTool.mouse.x)/100
				elseif  multiTool.name == "rotateY" then

					multiTool.angle 	= -(mouse.y - multiTool.mouse.y)/100
				end
				multiTool.angle 	= multiTool.angle==0 and multiTool.angle+0.0001 or multiTool.angle
			else
				trace("beet")
				local coords  = getPlaneCoords(multiTool.position,multiTool.axis)
				local v1 = coords - multiTool.position
				multiTool.angleDir = #selectedEntities>1 and -1 or 1

				multiTool.angle =    math.angle(0,0,
					vec3.dot(multiTool.startOri*
						multiTool.current.plane1,v1),
					vec3.dot(multiTool.startOri*
						multiTool.current.plane2,v1)) -  multiTool.startAngle
			end

		elseif multiTool.scaling then
			local dist = vec2.dot(vec2(mouse.x-multiTool.mouse.x,mouse.y-multiTool.mouse.y),vec2(1,-1))/10

			multiTool.scale = vec3(1/((dist+50)/50))
			if multiTool.screenScale then 
				
			else 
				
			end
		else 
			multiTool.mouse 		= {x=mouse.x,y=mouse.y}
		end

		editState 			= tooling and "Transforming" or "Normal"
		
		if not animationPanel.open and keypressed("backspace") then 
			editor.deleteSelected()
		end
	end 
end

function editor.getToolAngle()
	return math.angle(multiTool.screen.x,multiTool.screen.y,mouse.x,mouse.y)+pi/2 
end

function editor.getToolDist()
	return math.dist(multiTool.screen.x,multiTool.screen.y,mouse.x,mouse.y)
end

