--[[
	The purpose of this library is to facilitate working with third-party tool skins
	TODO: document how to use this
]]

function ListSkins(tool, priority)
	priority = priority or {}
	local skins = {}
	for _, key in ipairs( ListKeys( "mods.available" ) ) do
		local isLocal = key:find("^local%-")
		local path = GetString( "mods.available." .. key .. ".path" )
		if HasFile(string.format("RAW:%s/tool_skins/%s.lua", path, tool)) then
			local f = loadfile(string.format("%s/tool_skins/%s.lua", path, tool))
			if f then
				setfenv(f, {})
				local success, data = pcall(f)
				if success and type(data) == "table" then
					for id, info in pairs(data) do
						local shouldUse = true
						if skins[id] then
							local lver = tonumber(info.version) or 0
							local rver = tonumber(skins[id].version) or 0
							if lver == rver then
								if isLocal then lver = lver + 1 end
								if skins[id].isLocal then rver = rver + 1 end
							end
							if lver > rver then
								for i = 1, #skins do
									if skins[i] == skins[id] then
										table.remove(skins, i)
										skins[id] = nil
										break
									end
								end
							else
								shouldUse = false
							end
						end
						if shouldUse then
							info.id = id
							info.mod = key
							info.islocal = isLocal
							info.main = key .. ":" .. info.main:gsub("^MOD/", "")
							if info.icon then
								info.icon = string.format("RAW:%s/%s", path, info.icon:gsub("^MOD/", ""))
							end
							skins[#skins+1] = info
							skins[id] = info
						end
					end
				end
			end
		end
	end
	table.sort(skins, function(a, b)
		local diff = (priority[a.mod] or math.huge) - (priority[b.mod] or math.huge)
		return diff == 0 and (a.sort or math.huge) < (b.sort or math.huge) or diff < 0
	end)
	return skins
end

function ActivateSkin(tool, id, group)
	local success, skins = pcall(ListSkins, tool)
	if not success or not skins[id] then return false end
	local skin = skins[id]
	local skin_key = string.format("game.tool.%s.skin", tool)
	local skin_config_key = string.format("savegame.mod.skin.%s.", id)
	if HasKey(skin_key) then return true end
	SetString(skin_key, id)
	if skin.config then
		for key in pairs(skin.config) do
			if HasKey(skin_config_key .. key) then
				SetString(skin_key .. ".config." .. key, GetString(skin_config_key .. key))
			end
		end
	end
	if skin.customization then
		for i = 1, #skin.customization do
			local key = skin.customization[i].id
			if HasKey(skin_config_key .. key) then
				SetString(skin_key .. ".config." .. key, GetString(skin_config_key .. key))
			end
		end
	end
	SetInt(skin_key .. ".group", group)
	SetInt(skin_key .. ".script", Spawn(skin.main, Transform())[1])
	return true
end
