-- lx-bundle:true

-- This file is part of Lx, created by Liqube <www.liqube.com>
-- Copyright Liqube Audio. All rights reserved.
-- Lx Interim License. See LICENSE for details.

--- Shared image file detection helpers
-- Keeps supported image extension logic out of the viewer and open flow
-- @module core.image.support

local image_support = {}

local SUPPORTED_EXTENSIONS = {
	bmp = true,
	cur = true,
	gif = true,
	ico = true,
	icns = true,
	jfif = true,
	jpeg = true,
	jpg = true,
	pjp = true,
	pjpeg = true,
	png = true,
	qoi = true,
	svg = true,
	tga = true,
	xpm = true,
}

local FORMAT_NAMES = {
	cur = "CUR",
	gif = "GIF",
	ico = "ICO",
	icns = "ICNS",
	jfif = "JPEG",
	jpeg = "JPEG",
	jpg = "JPEG",
	pjp = "JPEG",
	pjpeg = "JPEG",
	png = "PNG",
	qoi = "QOI",
	svg = "SVG",
	tga = "TGA",
	xpm = "XPM",
}

--- Return one normalized supported image extension for a path
-- @param path string|nil file path
-- @return boolean supported true when the extension is supported
-- @return string|nil extension normalized lowercase extension
function image_support.is_supported(path)
	if type(path) ~= "string" or path == "" then
		return false, nil
	end

	-- A virtual suffix selects content inside the image rather than changing its file type
	path = system.parse_file_reference(path, false).filename

	-- Pattern breakdown:
	-- '%.'
	--   matches the final literal dot before the extension
	-- '([^.]+)'
	--   captures one or more non-dot chars as the extension
	-- '$'
	--   anchors the capture to the end of the path
	local extension = path:match("%.([^.]+)$")

	if not extension then
		return false, nil
	end

	extension = extension:lower()

	return SUPPORTED_EXTENSIONS[extension] == true, extension
end

--- Return the user-facing name for one supported image extension
-- @param extension string|nil normalized or raw extension
-- @return string|nil format_name
function image_support.get_format_name(extension)
	if type(extension) ~= "string" or extension == "" then
		return nil
	end

	local normalized = extension:lower()
	if SUPPORTED_EXTENSIONS[normalized] ~= true then
		return nil
	end

	return FORMAT_NAMES[normalized] or normalized:upper()
end

return image_support
