--[[
	Implementation
]]

local function isAlive()
	return maid.humanoid.Health > 0 and maid.humanoid:GetState() ~= Enum.HumanoidStateType.Dead
end

local function destroy()
	maid:destroy()
end

local function patrol()
	while isAlive() do
		if not attacking then
			local position = getRandomPointInCircle(startPosition, PATROL_RADIUS)
			maid.humanoid.WalkSpeed = PATROL_WALKSPEED
			maid.humanoid:MoveTo(position)
		end

		wait(random:NextInteger(MIN_REPOSITION_TIME, MAX_REPOSITION_TIME))
	end
end

local function isInstaceAttackable(targetInstance)
	local isAttackable = false
	
	local targetHumanoid = targetInstance and targetInstance.Parent and targetInstance.Parent:FindFirstChild("Humanoid")
	if not targetHumanoid then
		return false
	end

	-- Determine if they are attackable, depening on the attack mode
	local isEnemy = false
	if ATTACK_MODE == 1 then
		-- Attack characters with the SoldierEnemy tag
		if
			CollectionService:HasTag(targetInstance.Parent, "SoldierEnemy") and
			not CollectionService:HasTag(targetInstance.Parent, "SoldierFriend") then
			isEnemy = true
		end
	elseif ATTACK_MODE == 2 then
		-- Attack all humanoids without the SoldierFriend tag
		if not CollectionService:HasTag(targetInstance.Parent, "SoldierFriend") then
			isEnemy = true
		end
	elseif ATTACK_MODE == 3 then
		-- Attack all humanoids
		isEnemy = true
	end

	if isEnemy then
		local distance = (maid.humanoidRootPart.Position - targetInstance.Position).Magnitude
	
		if distance <= ATTACK_RADIUS then
			local ray = Ray.new(
				maid.humanoidRootPart.Position,
				(targetInstance.Parent.HumanoidRootPart.Position - maid.humanoidRootPart.Position).Unit * distance
			)
	
			local part = Workspace:FindPartOnRayWithIgnoreList(ray, {
				targetInstance.Parent, maid.instance,
			}, false, true)
	
			if
				targetInstance ~= maid.instance and
				targetInstance:IsDescendantOf(Workspace) and
				targetHumanoid.Health > 0 and
				targetHumanoid:GetState() ~= Enum.HumanoidStateType.Dead and
				not part
			then
				isAttackable = true
			end
		end		
	end

	return isAttackable
end

local function fireGun()
	-- Do damage to the target
	local targetHunanoid = target.Parent:FindFirstChild("Humanoid")
	targetHunanoid:TakeDamage(ATTACK_DAMAGE)

	-- Play the firing animation
	maid.attackAnimation:Play()

	-- Play the firing sound effect
	maid.gunFireSound:Play()

	-- Muzzle flash
	local firingPositionAttachment = maid.instance.Weapon.Handle.FiringPositionAttachment
	firingPositionAttachment.FireEffect:Emit(10)
	firingPositionAttachment.PointLight.Enabled = true

	wait(0.1)

	firingPositionAttachment.PointLight.Enabled = false
end

local function findTargets()
	-- Do a new search region if we are not already searching through an existing search region
	if not searchingForTargets and tick() - timeSearchEnded >= SEARCH_DELAY then
		searchingForTargets = true

		-- Create a new region
		local centerPosition = maid.humanoidRootPart.Position
		local topCornerPosition = centerPosition + Vector3.new(ATTACK_RADIUS, ATTACK_RADIUS, ATTACK_RADIUS)
		local bottomCornerPosition = centerPosition + Vector3.new(-ATTACK_RADIUS, -ATTACK_RADIUS, -ATTACK_RADIUS)

		searchRegion = Region3.new(bottomCornerPosition, topCornerPosition)
		searchParts = Workspace:FindPartsInRegion3(searchRegion, maid.instance, math.huge)

		newTarget = nil
		newTargetDistance = nil

		-- Reset to defaults
		searchIndex = 1
	end

	if searchingForTargets then
		-- Search through our list of parts and find attackable humanoids
		local checkedParts = 0
		while searchingForTargets and searchIndex <= #searchParts and checkedParts < MAX_PARTS_PER_HEARTBEAT do
			local currentPart = searchParts[searchIndex]
			if currentPart and isInstaceAttackable(currentPart) then
				local character = currentPart.Parent
				local distance = (character.HumanoidRootPart.Position - maid.humanoidRootPart.Position).magnitude

				-- Determine if the charater is the closest
				if not newTargetDistance or distance < newTargetDistance then
					newTarget = character.HumanoidRootPart
					newTargetDistance = distance
				end
			end

			searchIndex = searchIndex + 1

			checkedParts = checkedParts + 1
		end

		if searchIndex >= #searchParts then
			target = newTarget
			searchingForTargets = false
			timeSearchEnded = tick()
		end
	end
end

local function attack()
	attacking = true

	local originalWalkSpeed = maid.humanoid.WalkSpeed
	maid.humanoid.WalkSpeed = 0

	maid.attackIdleAnimation:Play()

	local shotsFired = 0
	while attacking and isInstaceAttackable(target) and isAlive() do
		fireGun()

		shotsFired = (shotsFired + 1) % CLIP_CAPACITY

		if shotsFired == CLIP_CAPACITY - 1 then
			wait(RELOAD_DELAY)
		else
			wait(ATTACK_DELAY)
		end
	end

	maid.humanoid.WalkSpeed = originalWalkSpeed

	maid.attackIdleAnimation:Stop()

	attacking = false
end