--[[
    Returns a HumanoidDescription representing the outfit that "player" is
    currently wearing, with the addition of one extra item given by "assetId".

    The "assetType" parameter represents which kind of accessories the new one
    belongs to. It must be the name of a property under HumanoidDescription. If
    the user is already wearing items of that type, those are removed first.

    In case of a failure to retrieve "player"'s current outfit, a generic
    character look is generated.
]]


local MerchBooth = script:FindFirstAncestor("MerchBooth")

local Cryo = require(MerchBooth.Packages.Cryo)
local matchAssetTypeToAccessoryType = require(MerchBooth.Modules.matchAssetTypeToAccessoryType)
local isAccessory = require(MerchBooth.Modules.isAccessory)
local isClassicClothing = require(MerchBooth.Modules.isClassicClothing)

local DEFAULT_BODY_COLOR = Color3.fromRGB(122, 122, 122)

local function generateDescriptionWithItem(player: Player, assetId: number, assetType: Enum.AssetType)
	local character = player and player.Character
	local humanoid = character and character:FindFirstChildOfClass("Humanoid")
	local description = humanoid and humanoid:GetAppliedDescription()

	-- We could run into the "no description" case if, for instance, the game
	-- has characters disabled. In which case, we want a new description with
	-- character colors set to grey (default is black and isn't very visible in
	-- the default dark theme).
	if not description then
		description = Instance.new("HumanoidDescription")
		description.HeadColor = DEFAULT_BODY_COLOR
		description.TorsoColor = DEFAULT_BODY_COLOR
		description.LeftArmColor = DEFAULT_BODY_COLOR
		description.RightArmColor = DEFAULT_BODY_COLOR
		description.LeftLegColor = DEFAULT_BODY_COLOR
		description.RightLegColor = DEFAULT_BODY_COLOR
	end

	if isAccessory(assetType) then
		local accessoryTypeEnum = matchAssetTypeToAccessoryType(assetType)
		local accessories = Cryo.List.filter(description:GetAccessories(true), function(accessory)
			return accessory.AccessoryType ~= accessoryTypeEnum
		end)
		table.insert(accessories, {
			Order = 1,
			AssetId = assetId,
			AccessoryType = accessoryTypeEnum,
		})
		description:SetAccessories(accessories, true)
	elseif isClassicClothing(assetType) then
		if assetType == Enum.AssetType.TShirt then
			description.GraphicTShirt = assetId
		elseif assetType == Enum.AssetType.Shirt then
			description.Shirt = assetId
		elseif assetType == Enum.AssetType.Pants then
			description.Pants = assetId
		end
	end

	return description
end

return generateDescriptionWithItem
