local LrTasks = import("LrTasks")
local LrPathUtils = import("LrPathUtils")
local LrFileUtils = import("LrFileUtils")
local LrApplication	= import "LrApplication"

g_MPExtrasPluginAppName_extrasCollections = nil

--Import Section--------------------------------------------------------------------------

function tryToImportFromFile(fileName)
	if LrFileUtils.exists(fileName) then
		LrTasks.startAsyncTask(function(context)
			local catalog = LrApplication.activeCatalog()
			local photo = nil;
			catalog:withWriteAccessDo("0",
				function(context)
					photo = catalog:addPhoto(fileName, nil, nil)
				  	if photo ~= nil then
						if g_MPExtrasPluginAppName_extras_keyrwords ~= nil then
							local currentKeywords = photo:getRawMetadata("keywords")
							if (numberOfElementsInArray(currentKeywords) == 0) and (numberOfElementsInArray(g_MPExtrasPluginAppName_extras_keyrwords) > 0) then
								for k, v in pairs(g_MPExtrasPluginAppName_extras_keyrwords) do
									photo:addKeyword(v)
								end
							end
							g_MPExtrasPluginAppName_extras_keyrwords = nil
						end
						if g_MPExtrasPluginAppName_extrasCollections ~= nil then
							for k, v in pairs(g_MPExtrasPluginAppName_extrasCollections) do
								v:addPhotos({photo})
							end
							g_MPExtrasPluginAppName_extrasCollections = nil						
						end
					end
				end
			)
			if photo ~= nil then
				catalog:setSelectedPhotos(photo, {photo})
			end
		end)
	end
end

local standardTempDirPath = LrPathUtils.getStandardFilePath('temp')
local importFileName = LrPathUtils.child(standardTempDirPath, "ImportMPExtrasPluginAppName")

tryToImportFromFile(importFileName)

--g_MPExtrasPluginAppName_isPluginRunning is used since async task can be running even after plug-in shutdown
g_MPExtrasPluginAppName_isPluginRunning = 1

LrTasks.startAsyncTask(function()
	while g_MPExtrasPluginAppName_isPluginRunning == 1 do
		if LrFileUtils.exists(importFileName) then
			local photoPath = LrFileUtils.readFile(importFileName)
			tryToImportFromFile(photoPath)
			LrFileUtils.delete(importFileName)
		end
		--sleep for 1 second
		LrTasks.sleep(1)
  end
end)
