--[[ Shared preview export: downsized JPEGs that detect.py reads. ]]

local LrExportSession = import 'LrExportSession'
local LrPrefs = import 'LrPrefs'

local prefs = LrPrefs.prefsForPlugin()

local Export = {}

-- Bigger previews snap edges more precisely but export and detect slower;
-- the pref is clamped so a typo can't produce absurd exports.
local function maxPixels()
	local n = tonumber(prefs.maxPixels) or 1500
	return math.max(600, math.min(6000, n))
end

-- Renders `photos` into `tempDir` and returns { {photo=..., path=...} or
-- {photo=..., failure=...}, ... }. `scope` is optional; when given, the
-- loop stops early if it is canceled.
function Export.previews(photos, tempDir, scope)
	local session = LrExportSession({
		photosToExport = photos,
		exportSettings = {
			LR_export_destinationType = 'specificFolder',
			LR_export_destinationPathPrefix = tempDir,
			LR_export_useSubfolder = false,
			LR_format = 'JPEG',
			LR_jpeg_quality = 0.9,
			LR_export_colorSpace = 'srgb',
			LR_size_doConstrain = true,
			LR_size_maxWidth = maxPixels(),
			LR_size_maxHeight = maxPixels(),
			LR_size_units = 'pixels',
			LR_collisionHandling = 'rename',
			LR_includeVideoFiles = false,
			LR_removeLocationMetadata = true,
			LR_reimportExportedPhoto = false,
		},
	})

	local rendered = {} -- { {photo=..., path=...}, ... }
	for _, rendition in session:renditions() do
		if scope and scope:isCanceled() then
			break
		end
		local success, pathOrMessage = rendition:waitForRender()
		if success then
			rendered[#rendered + 1] = { photo = rendition.photo, path = pathOrMessage }
		else
			rendered[#rendered + 1] = {
				photo = rendition.photo,
				failure = 'export failed: ' .. tostring(pathOrMessage),
			}
		end
	end
	return rendered
end

return Export
