-- 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, appName)
	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
			)
			local CKCollection = nil
			catalog:withWriteAccessDo("1",
				function(context)
				  CKCollection = catalog:createCollectionSet("Macphun Creative Kit", nil, true)
				end
			)

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

		end)
	end
end

local standardTempDirPath = LrPathUtils.getStandardFilePath('temp')
local importFileNames = MPExtrasImportFileNames


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

LrTasks.startAsyncTask(function()
	while g_isExtrasCKPluginRunning == 1 do
		for importFileName, appName in pairs(importFileNames) do
			local path = LrPathUtils.child(standardTempDirPath, importFileName)
			if LrFileUtils.exists(path) then
				local photoPath = LrFileUtils.readFile(path)
				tryToImportFromFile(photoPath, appName)
				LrFileUtils.delete(path)
			end
		end
		--sleep for 1 second
		LrTasks.sleep(1)
  end
end)
