--Combat Variables--
local munition = combat.resetMunition()
local lastAttack = tick()
local target = nil

if not _G.ApachePathing then
	pathing.init()
end

function takeOff()
	startEngine()
	criticalAction = true
	while flight.checkHeight(desiredHeight) == 1 do
		wait(0.2)
	end
	criticalAction = false
end

function startEngine()
	bp.Position = body.Position
	bp.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
	bg.CFrame = myRoot.CFrame
	bg.MaxTorque = bgTorque
	
	body.BackBladeHinge.AngularVelocity = 1000
	body.FrontBladeHinge.AngularVelocity = 1000
	local soundTween = game:GetService("TweenService"):Create(body.Sound,TweenInfo.new(5),{Volume = 1})
	soundTween:Play()
	wait(5)
	engineRunning = true
end

function killEngine()
	engineRunning = false
	bp.MaxForce = Vector3.new()
	body.BackBladeHinge.AngularVelocity = 0
	body.FrontBladeHinge.AngularVelocity = 0
	body.FrontBladeHinge.AngularSpeed = 0
	game:GetService("TweenService"):Create(script.Parent["Main Propeller"],TweenInfo.new(5),{AssemblyAngularVelocity = Vector3.new()}):Play()
	local soundTween = game:GetService("TweenService"):Create(body.Sound,TweenInfo.new(5),{Volume = 0})
	soundTween:Play()
	wait(5)
	bg.MaxTorque = Vector3.new()
end

function findTurns(waypoints)
	local importantWaypoints = {}
	table.insert(importantWaypoints,waypoints[1])
	
	local index = 0
	local canseeIndex = 1
	local currentWaypoint = importantWaypoints[1]
	while true do
		if canseeIndex ~= #waypoints then
			local lookCFrame = CFrame.lookAt(currentWaypoint.Position,waypoints[canseeIndex].Position)
			for offset = -15, 15, 5 do
				local params = RaycastParams.new()
				params.FilterDescendantsInstances = {script.Parent}
				local tempCFrame = lookCFrame * CFrame.new(offset,0,0)
				local dist = core.checkDist(tempCFrame.Position,waypoints[canseeIndex])
				local result = workspace:Raycast(tempCFrame.Position,tempCFrame.LookVector*dist,params)
				
				if result then
					
					currentWaypoint = waypoints[canseeIndex]
					table.insert(importantWaypoints,waypoints[canseeIndex-1])
					break
				end
			end
			canseeIndex = canseeIndex + 1
		else
			table.insert(importantWaypoints,waypoints[canseeIndex])
			break
		end 
	end
	
	return importantWaypoints
end

function flyPath(pos)

	local waypoints = pathing.findPath(myRoot.Position,pos)
	
	if not waypoints then
		warn("No valid path to target")
		wait(30)
		return false
	end
	
	waypoints = findTurns(waypoints)

	local timeout = core.checkDist(myRoot,pos)
	local killPath = false
	if waypoints then
		for _,waypoint in ipairs(waypoints) do
			
			local currentTarget = target 
			
			--While flying to next point
			while not flight.flyToPos(waypoint.Position) and not dodgingObstacles.Value do
				
				if currentTarget ~= target or (target and not combat.getMunition(munition)) then
					killPath = true
					break
				end
				
				timeout = timeout - 1
				if timeout < 0 then
					killPath = true
					break
				end
				wait()
			end
			if killPath then
				break
			end
		end
	end
end

function combatFlight()
	if core.checkSight(target) then

		local turnAngle = core.findAngle(myRoot.Position,target.Position,myRoot)
		if core.checkDistXZ(myRoot,target) > 25 then
			--Angles the helicopter to fly towards the target

			flight.flyTowards(-35,-turnAngle)
		else
			flight.flyTowards(0,-turnAngle)
		end
	else

		flyPath(target.Position)

	end

	--When too close to target fly forward to gain some distance
	if target and core.checkDistXZ(target,myRoot) < 50 then
		for i = 1, 20 do
			wait()
			flight.flyTowards(-25,0)
			if dodgingObstacles.Value then
				break
			end
		end
	end
end

function flyHome()
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {script.Parent}
	local dist = (myRoot.Position-home.Position).Magnitude
	local result = workspace:Raycast(myRoot.Position,(home.Position - myRoot.Position).Unit * dist, params)
	if not result then
		if flight.flyToPos(home.Position) then

			criticalAction = true
			engineRunning = false
			flight.land(home)

			--Once we completely land we are available for other missions
			if core.checkDist(home.Position,myRoot) < 30 then
				criticalAction = false 
				munition = combat.resetMunition()
				killEngine()
			end
		end
	else
		flyPath(home.Position)
	end
end

function crash()
	body.BladeAttach.Smoke.Enabled = true
	body.RearBladeAttach.Smoke.Enabled = true

	flight.flyTowards(math.random(-80,80),nil,math.random(-80,80))

	for i = 1, math.random(4,10) do

		local posX = math.random(-body.Size.X,body.Size.X)
		local posY = math.random(-body.Size.Y,body.Size.Y)
		local posZ = math.random(-body.Size.Z,body.Size.Z)/3
		local pos = Vector3.new(posX,posY,posZ)
		pos = pos/2

		local attach = Instance.new("Attachment")
		attach.Parent = body
		attach.Position = pos

		local fire = Instance.new("Fire")
		--fire.Parent = attach
		fire.Size = math.random(3,8)
		fire.Heat = math.random(math.random(10,20))
	end

	bg.MaxTorque = Vector3.new(100,100,100)
	
	local crashSpeed = math.random(1,3)/5
	local crashed = false
	body.Touched:Connect(function(part)
		if part:GetMass() > 50 or part:IsGrounded() then
			crashed = true
		end
	end)
	local maxIterations = 200
	while not crashed do
		flight.physics()
		bp.Position = bp.Position - Vector3.new(0,crashSpeed,0)
		maxIterations = maxIterations - 1
		if maxIterations < 0 then
			break
		end
		wait()
	end
	
	body.Sound:Stop()
	bp:Destroy()
	bg:Destroy()

	body.FrontBladeHinge:Destroy()
	body.BackBladeHinge:Destroy()
	script.Parent["Main Propeller"].CanCollide = false

	local x = Instance.new("Explosion")
	x.Parent = myRoot
	x.BlastRadius = 50
	x.BlastPressure = 0
	x.DestroyJointRadiusPercent = 0
	x.Position = myRoot.Position
end