#include "script/common.lua"
pAmmo = GetIntParam("ammo",3)
pGun = GetBoolParam("gun",false)

function init()
    cabmotor = FindJoint("cabmotor")
    armmotor = FindJoint("armmotor")    

	armSnd = LoadLoop("snd/turretarm.ogg")
	hutSnd = LoadLoop("snd/turrethut.ogg")
	
    armTurn = 0    
    armSpeed = 0.3

    hutTurn = 0
    hutSpeed = 0.6

	armAngleMin, armAngleMax = GetJointLimits(armmotor)
	armAngle = GetJointMovement(armmotor)
    SetJointMotorTarget(armmotor, armAngle, 1.0, 1000.0)
    SetJointMotorTarget(cabmotor, 0, 1000.0)
	
	armCurrent = GetJointMovement(armmotor)
	hutCurrent = GetJointMovement(cabmotor)

    --tank
    ammo = pAmmo
	reach = 2500
	reloadTime = 0

	explosionSize = 1.5

	didImpact = false
	impactPoint = Vec(0,0,0)

	projectileTime = 0.0
	projectileTimeMax = 0.3
	projectilePos = Vec(0,0,0)
	projectileStartPos = Vec(0,0,0)
	projectileHitPos = Vec(0,0,0)

    direction = Vec(0,0,0)

    armBody = FindBody("arm")    
    armTransform = GetBodyTransform(armBody)
	
	SetTag(armBody, "interact", "Operate")

    muzzleLocation = FindLocation("muzzle")
    muzzleTransform = GetLocationTransform(muzzleLocation)
    localMuzzlePos = TransformToLocalPoint(armTransform, muzzleTransform.pos)

    
    directionLocation = FindLocation("direction")
    directionTransform = GetLocationTransform(directionLocation)
    localDirectionPos = TransformToLocalPoint(armTransform, directionTransform.pos)

	if pGun then
		shootSnd = LoadSound("tools/gun0.ogg")
	else
		shootSnd = LoadSound("tools/tankgun0.ogg")
	end
	
	active = false
	
	localCameraTransform = GetLocationTransform(FindLocation("camera"))
	localCameraTransform = TransformToLocalTransform(GetBodyTransform(armBody), localCameraTransform)
	cameraAnim = 0
	recoil = 0
end
    
function tick(dt)
    if active then  
		SetBool("game.disablemap", true)
		SetBool("game.disablepause", true)
		SetBool("game.player.disableinput", true)
		
		if InputPressed("interact") or InputPressed("esc") then
			active = false
			SetTag(armBody, "interact", "Operate")
			SetValue("cameraAnim", 0.0, "cosine", 0.5)
			local t = GetPlayerTransform()
			t.rot = GetBodyTransform(armBody).rot
			SetPlayerTransform(t)
		end
        armTransform = GetBodyTransform(armBody)
        worldMuzzlePos = TransformToParentPoint(armTransform,localMuzzlePos)
        worldDirectionPos = TransformToParentPoint(armTransform,localDirectionPos)

        direction = VecSub(worldDirectionPos, worldMuzzlePos)
        direction = VecNormalize(direction)

        shoot(dt)
        if projectileTime > 0 then
            projectileTime = projectileTime - dt
            projectTilePos = VecLerp(projectileHitPos, projectileStartPos, projectileTime/projectileTimeMax)
            SpawnParticle("smoke", projectTilePos, VecScale(VecNormalize(VecSub(projectTilePos,projectileHitPos)),2), 1, 0.5)
            PointLight(projectTilePos, 0.5, 0.5, 0.5, math.random(1,15))
        elseif didImpact then
            didImpact = false
            Explosion(impactPoint,explosionSize)
        end
	else
		if GetPlayerInteractBody() == armBody and InputPressed("interact") then
			active = true
			RemoveTag(armBody, "interact")
			SetValue("cameraAnim", 1.0, "cosine", 0.5)
		end
    end

	if cameraAnim > 0 then
		local pt = GetPlayerCameraTransform()
		local lt = TransformCopy(localCameraTransform)
		lt.pos = VecAdd(lt.pos, Vec(0, 0, -0.5*recoil))
		local ct = TransformToParentTransform(GetBodyTransform(armBody), lt)
		SetCameraTransform(Transform(VecLerp(pt.pos, ct.pos, cameraAnim), QuatSlerp(pt.rot, ct.rot, cameraAnim)))
	end
	
end

function update(dt)
	if active then
		local armTurnTarget = 0
		if InputDown("down") then            
			armTurnTarget = -1.0
		elseif InputDown("up") then            
			armTurnTarget = 1.0
		end
		armTurn = armTurn + clamp(armTurnTarget-armTurn, -0.06, 0.06)

		local current = GetJointMovement(armmotor)
		armAngle = clamp(armAngle, current-5, current+5)
		armAngle = clamp(armAngle + armTurn*armSpeed*180.0/math.pi*dt, armAngleMin, armAngleMax)
		
		local hutTurnTarget = 0
		if InputDown("right") then            
			hutTurnTarget = 1.0
		elseif InputDown("left") then            
			hutTurnTarget = -1.0
		end
		hutTurn = hutTurn + clamp(hutTurnTarget-hutTurn, -0.06, 0.06)
		
		local ac = GetJointMovement(armmotor)
		local av = math.abs(armCurrent - ac)
		armCurrent = ac
		local hc = GetJointMovement(cabmotor)
		local hv = math.abs(hutCurrent - hc)
		hutCurrent = hc

		if av > 0.1 then PlayLoop(armSnd, GetPlayerPos(), av*3) end
		if hv > 0.1 then PlayLoop(hutSnd, GetPlayerPos(), hv*3) end

		SetJointMotorTarget(armmotor, armAngle, 1.0, 1000)
		SetJointMotor(cabmotor, hutTurn * hutSpeed, 1000)        
	else
		SetJointMotorTarget(armmotor, armAngle, 1.0, 1000)
		SetJointMotor(cabmotor, 0, 1000)        
	end
end

function shoot(dt)
	if pGun then
		if reloadTime > 0 then
			reloadTime = reloadTime - dt
			return
		end

		if InputDown("usetool") then
			if ammo > 0  or GetInt("level.sandbox") == 1 then	
				Shoot(worldMuzzlePos,direction,0)
				
				PlaySound(shootSnd)
				reloadTime = 0.042
				ammo = ammo - 1
				
				SpawnParticle("smoke", worldMuzzlePos, VecScale(direction,3), 2, 5)
				PointLight(worldMuzzlePos,1,1,1,math.random()+3)
			end
		end
	else
		QueryRejectBody(armBody)
		local hit, dist, normal, shape = QueryRaycast(worldMuzzlePos, direction, reach)
		
		hitPoint = VecAdd(worldMuzzlePos, VecScale(direction, dist))
		projectileHitPos = VecCopy(hitPoint)

		if hit then
			DrawLine(worldMuzzlePos, hitPoint, 1, 0, 0, 0.2)
			PointLight(hitPoint,1, 0.1, 0.1, 0.2+0.1*math.random())
		else
			DrawLine(worldMuzzlePos, VecAdd(worldMuzzlePos,VecScale(direction, reach)), 1, 0, 0, 0.2)
		end

		if reloadTime > 0 then
			reloadTime = reloadTime - dt
			return
		end


		if InputPressed("usetool") then
			if ammo > 0 or GetInt("level.sandbox") == 1 then	
				
				recoil = 1.0
				SetValue("recoil", 0, "easeout", 1.0)
				
				--animate projectile light
				projectileTime = projectileTimeMax				
				projectilePos = VecCopy(worldMuzzlePos)
				projectileStartPos = VecCopy(worldMuzzlePos)

				PlaySound(shootSnd)
				reloadTime = 1
				ammo = ammo - 1
				
				SpawnParticle("smoke", worldMuzzlePos, VecScale(direction,3), 2, 5)
				
				didImpact = hit
				
				if hit then
					hitPoint = VecAdd(worldMuzzlePos, VecScale(direction, dist))
					impactPoint = VecCopy(hitPoint)
					projectileHitPos = VecCopy(hitPoint)
				else
					projectileHitPos = VecAdd(worldMuzzlePos,VecScale(VecNormalize(direction),50))--reach/4)
				end
			end
		end
	end	
end

function draw(dt)
	if active and GetString("level.state") == "" then
		drawTool()
	end
end

function drawTool()
	UiPush()
		UiTranslate(UiCenter(), UiHeight()-70)
		UiAlign("top left")
		UiPush()
			UiFont("bold.ttf", 26)
			UiAlign("center")	
			UiScale(1)
			UiTextOutline(0,0,0,1, 0.1)
			UiColor(1, 1, 1, 1.0)			
			UiText("TURRET")
			UiTranslate(0, -24)
			if w == t then UiScale(1.6) end
			if ammo < 2001 and GetInt("level.sandbox") ~= 1 then
				local a = math.floor(ammo)
				UiText(a)
			end
		UiPop()
		UiTranslate(150, 0)
	UiPop()
end

