local LrApplication = import("LrApplication")
local LrTasks = import("LrTasks")
local LrPathUtils = import("LrPathUtils")
local LrFileUtils = import("LrFileUtils")
local LrStringUtils = import("LrStringUtils")
g_MPExtrasPluginAppName_extras_keyrwords = nil

LrTasks.startAsyncTask(function()
	local catalog = LrApplication.activeCatalog()
	local tPhoto = catalog:getTargetPhoto()
	if tPhoto
	then
		local tPhotoPath = tPhoto.path
		local standardTempDirPath = LrPathUtils.getStandardFilePath('temp')
		local importFileName = LrPathUtils.child(standardTempDirPath, "ImportMPExtrasPluginAppName")

		if LrFileUtils.exists(importFileName)
		then
		  LrFileUtils.delete(importFileName)
		end
		local command = "MPLightroomBridgePath \"" .. tPhotoPath .. "\" -MPLightroomExtrasPluginResPath " .. importFileName
		local tPhotos = catalog:getTargetPhotos()
		g_MPExtrasPluginAppName_extrasCollections = nil
		if tPhotos
		then
			local size = 0
			for index, photo in pairs(tPhotos) do
				size = size + 1
				if g_MPExtrasPluginAppName_extrasCollections == nil then
					g_MPExtrasPluginAppName_extrasCollections = photo:getContainedCollections()
				else
					g_MPExtrasPluginAppName_extrasCollections = intersectArrays(g_MPExtrasPluginAppName_extrasCollections, photo:getContainedCollections())
				end
				if g_MPExtrasPluginAppName_extras_keyrwords == nil then
					g_MPExtrasPluginAppName_extras_keyrwords = photo:getRawMetadata("keywords")
				else
					g_MPExtrasPluginAppName_extras_keyrwords = intersectArrays(g_MPExtrasPluginAppName_extras_keyrwords, photo:getRawMetadata("keywords"))
				end
			end
			if size > 1
			then
				local collection = ""
				for index, photo in pairs(tPhotos) do
					local photoPath = photo.path
					collection = collection .. string.len(photoPath) .. ":" .. photoPath
				end
				if string.len(collection) > 0 then
					command = command .. " -MPPhotoCollection " .. LrStringUtils.encodeBase64(collection)
				end
			end
		end
		LrTasks.execute(command)
	end
end)
