--Services

local pathfindingService = game:GetService("PathfindingService")
local runService = game:GetService("RunService")

local modules = script.Parent
local core = require(modules.CoreModule)
local status = require(modules.Status)
local troubleshoot = require(modules.Troubleshoot)

local marine = script.Parent.Parent.Parent
local myHuman = marine.Humanoid
local myRoot = marine.HumanoidRootPart


local moveEvent = Instance.new("BindableEvent")
function movement.moveToFinished()
	local success = true
	local completed = false
    
    core.spawn(function() 
        wait(1)
		if not completed then
	        success = false
	        moveEvent:Fire()   
		end
    end)
    
    core.spawn(function()
        myHuman.MoveToFinished:Wait()
        moveEvent:Fire()
    end)
    
	moveEvent.Event:Wait()

	completed = true

    return success
end

local path = pathfindingService:CreatePath()
function movement.pathToLocation(target)
	if not target or not target.Parent then return end
	
	path:ComputeAsync(myRoot.Position, target.Position)
	
	if path.Status == Enum.PathStatus.NoPath then
		return
	end
	
	local waypoints = path:GetWaypoints()
	
	--Make sure that path is actually valid
	if waypoints[1] and core.checkDist(waypoints[1],myRoot) > 10 then
		runService.Heartbeat:Wait()
		movement.pathToLocation(target)
	end
	
	troubleshoot.visualizePath(path)
	
	for _,waypoint in ipairs(waypoints) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			myHuman.Jump = true
		end
		myHuman:MoveTo(waypoint.Position)
		core.spawn(function()
			while myHuman.WalkToPoint.Y > myRoot.Position.Y - 1 do
				wait(0.1)
				myHuman.Jump = true
			end
		end)
		local moveSuccess = movement.moveToFinished()
		local dist = core.checkDist(myRoot,target)
		local canSee = core.checkSight(target)
		if not moveSuccess or not target.Parent or (dist < 30 and canSee) or status:get("currentTarget") ~= target then
			break
		elseif (core.checkSight(target) and target.Position.Y <= myRoot.Position.Y-5) then
			myHuman:MoveTo(myRoot.Position)
			break
		end
		if core.checkDist(target,waypoints[#waypoints]) > 30 then
			--movement.pathToLocation(target)
			break
		end
	end
end

function movement.walkRandom()
	local randX = math.random(-100,100)
	local randZ = math.random(-100,100)
	local goal = myRoot.Position + Vector3.new(randX, 0, randZ)
	local path = pathfindingService:CreatePath()
	path:ComputeAsync(myRoot.Position, goal)
	local waypoints = path:GetWaypoints()
	
	if path.Status == Enum.PathStatus.Success then
		for i,waypoint in ipairs(waypoints) do
			if waypoint.Action == Enum.PathWaypointAction.Jump then
				myHuman.Jump = true
			end
			myHuman:MoveTo(waypoint.Position)
			core.spawn(function()
				wait(0.5)
				if myHuman.WalkToPoint.Y > myRoot.Position.Y then
					myHuman.Jump = true
				end
			end)
			local moveSuccess = myHuman.MoveToFinished:Wait()
			if not moveSuccess or status:get("currentTarget") then
				break
			end
		end
	else
		wait(2)
	end
end
