-- Lightroom SDK
local LrFileUtils	= import "LrFileUtils"
local LrApplication	= import "LrApplication"
local LrTasks		= import 'LrTasks'
local LrPathUtils	= import 'LrPathUtils'
local LrDate		= import 'LrDate'

function tryToImportFromFile(fileName)
	if LrFileUtils.exists(fileName) then
		LrTasks.startAsyncTask(function(context)
			local catalog = LrApplication.activeCatalog()
			local currentTime = LrDate.currentTime()
			local formattedDate = LrDate.formatMediumDate(currentTime)
			local formattedTime = LrDate.formatMediumTime(currentTime)
			local newCollectionName = formattedDate.. " - " .. formattedTime
			local collection = nil
			local importedCollection = nil
			local photo = nil;
			catalog:withWriteAccessDo("0",
				function(context)
				  photo = catalog:addPhoto(fileName, nil, nil)
				end
			)

			catalog:withWriteAccessDo("1",
				function(context)
				  collection = catalog:createCollectionSet("MPExtrasAppName", nil, true)
				end
			)
			catalog:withWriteAccessDo("2",
				function(context)
				  importedCollection = catalog:createCollection(newCollectionName, collection, true)
				end
			)
			catalog:withWriteAccessDo("3",
				function(context)
				  importedCollection:addPhotos({photo})
				end
			)
			catalog:setActiveSources(importedCollection)

		end)
	end
end

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

tryToImportFromFile(importFileName)

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

LrTasks.startAsyncTask(function()
	while g_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)
