local LrTasks = import("LrTasks")
local LrPathUtils = import("LrPathUtils")
local LrXml= import("LrXml")
local LrFileUtils = import("LrFileUtils")
local LrApplication	= import "LrApplication"
local LrDate = import 'LrDate'

g_MPExtrasPluginAppName_presets = {}
g_MPExtrasPluginAppName_presetGroups = {}
g_MPExtrasPluginAppName_presetsLoaded = false


function loadPresets()
	local standardTempDirPath = LrPathUtils.getStandardFilePath('temp')
	local presetsInfoFilePath = LrPathUtils.child(standardTempDirPath, "MPExtrasPluginAppNameExtrasPresetsInfo.xml")
	LrFileUtils.delete(presetsInfoFilePath)

	local command =  "MPLightroomBridgePath" .. " -MPExportPresets \"" .. presetsInfoFilePath .. "\"" .. " -MPWait" .. " -MPAppBundlePath \"" .. "MPAppBundlePathTemplateKeyword\""

	LrTasks.execute(command)

	local f = io.open(presetsInfoFilePath, 'r')
	if not f then
		return {}
	end
	local xml = f:read('*a')
	f:close()


	local root = LrXml.parseXml(xml)
	local parsedRoot = parseNode(root)
	if parsedRoot ~= nil then
		local count = 0
		for Index, Value in pairs( parsedRoot ) do
		  count = count + 1
		end

		local index = 1
		while index <= count do
			local groupName = parsedRoot[index]
			index = index + 1
			if index > count then break end
			local presets = parsedRoot[index]
			table.insert(g_MPExtrasPluginAppName_presetGroups, groupName)
			table.insert(g_MPExtrasPluginAppName_presets, presets)
			index = index + 1
		end
	end
	g_MPExtrasPluginAppName_presetsLoaded = true
end

function parseNode(node)
	local result = nil
	local nodeName = node:name()
	if nodeName == "plist" then
		local count = node:childCount()
		if count == 1 then
			local child = node:childAtIndex(1)
			result = parseNode(child)
		end
	elseif nodeName == "string" then
		result = node:text()
	elseif nodeName == "array" then
		result = {}
		local count = node:childCount()
		local index = 1
		while index <= count do
			local parsedChild = parseNode(node:childAtIndex(index))
			if parsedChild ~= nil then
				table.insert(result, parsedChild)
			end
			index = index + 1
		end
	elseif nodeName == "dict" then
		result = {}
		local count = node:childCount()
		local index = 1
		while index <= count do
			local keyNode = node:childAtIndex(index)
			local keyNodeName = keyNode:name()
			if keyNodeName == "key" then
				local key = keyNode:text()
				index = index + 1
				if index > count then break end
				local value = parseNode(node:childAtIndex(index))
				if value ~= nil then
					result[key] = value
				end
			end
			index = index + 1
		end
	end

	return result
end

if MPExtrasSupportPresetsExport then
	LrTasks.startAsyncTask(function() 
		loadPresets()
	end)
end

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

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_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)

