local LrPathUtils = import("LrPathUtils")
local LrTasks = import("LrTasks")
local LrFileUtils = import("LrFileUtils")
local LrView = import("LrView")
local LrDate = import("LrDate")
local LrDialogs = import("LrDialogs")

local ExportProcessRenderedPhotos = {}

ExportProcessRenderedPhotos.exportPresetFields = {
	{ key = 'hide',		default = true },
	{ key = 'presetGroup',	default = 1 },
	{ key = 'preset', default = 1 },
}


ExportProcessRenderedPhotos.allowFileFormats = {'JPEG','TIFF', 'ORIGINAL'}

ExportProcessRenderedPhotos.allowColorSpaces = {'sRGB', 'ProPhotoRGB'}

function ExportProcessRenderedPhotos.processRenderedPhotos( functionContext, exportContext )

	local presets = g_MPExtrasPluginAppName_presets
	
	local selectedGroup = exportContext.propertyTable.presetGroup
	local groupPresets = nil
	if selectedGroup >= 2 then
		groupPresets = presets[selectedGroup - 1]
	end
	
	local selectedPreset = nil
	if groupPresets ~= nil then
		selectedPreset = groupPresets[exportContext.propertyTable.preset]
	end
	
	local exportSession = exportContext.exportSession

	-- Make a local reference to the export parameters.
	
	local exportParams = exportContext.propertyTable
	
	-- Set progress title.

	local nPhotos = exportSession:countRenditions()

	local progressScope = exportContext:configureProgress{
						title = nPhotos > 1
									and LOC( "$$$/MPExtrasPluginAppName/Upload/Progress=Uploading ^1 photos to MPExtrasAppName", nPhotos )
									or LOC ("$$$/MPExtrasPluginAppName/Upload/Progress/One=Uploading one photo to MPExtrasAppName"),
					}

	-- Save off uploaded photo IDs so we can take user to those photos later.
	
	local uploadedPhotoIds = {}

	for i, rendition in exportContext:renditions{ stopIfCanceled = true } do
	
		-- Get next photo.

		local success, pathOrMessage = rendition:waitForRender()
		
		-- Check for cancellation again after photo has been rendered.
		
		if progressScope:isCanceled() then break end
		
		if success then
			local command = "MPLightroomBridgePath" .. " \"" .. pathOrMessage .. "\"" .. " -MPWait"
			if selectedPreset ~= nil then
				command = command .. " -MPPresetName " .. "\"" .. selectedPreset.name .. "\"" .. " -MPPresetID " .. "\"" .. selectedPreset.id .. "\""
			end
			local hideWindow = exportContext.propertyTable.hide
			if hideWindow == true then
				command = command .. " -MPHideWindow"
			end
			LrTasks.execute(command)
		end
		
	end
end

local lPresetsLoaded = false

function ExportProcessRenderedPhotos.startDialog( propertyTable )
	if MPExtrasSupportPresetsExport then
		lPresetsLoaded = false
		local startTime = LrDate.currentTime()
		while not g_MPExtrasPluginAppName_presetsLoaded do
			local currentTime = LrDate.currentTime()
			if currentTime - startTime > 5 then 
				LrDialogs.message("Could not load presets for MPExtrasAppName")
				break
			end
		end
		if g_MPExtrasPluginAppName_presetsLoaded then
			lPresetsLoaded = true
			local presets = g_MPExtrasPluginAppName_presets
			local group = propertyTable.presetGroup
			local groupPresets = nil
			if group == nil then
				propertyTable.presetGroup = 1
				group = 1
			else 
				if type(group) ~= "number" then
					propertyTable.presetGroup = 1
					group = 1
				end
			end
			if group >= 2 then
				groupPresets = presets[group - 1]
			end
			if groupPresets ~= nil then
				if #groupPresets == 0 then
					propertyTable.presetGroup = 1
				end
			else
				propertyTable.presetGroup = 1
				propertyTable.hide = false
			end
		end
	end
end


function ExportProcessRenderedPhotos.sectionsForTopOfDialog( viewFactory, propertyTable )
	local result = nil
	if MPExtrasSupportPresetsExport then
		if not lPresetsLoaded then
			return nil
		end
		local groupItems = {}
		local groups = g_MPExtrasPluginAppName_presetGroups
		local count = 0
		
		count = count + 1
		table.insert(groupItems, {title = LOC( "$$$/MPExtrasPluginAppName/Export/None=None" ), value = count})


		for index, groupName in pairs(groups) do 
			count = count + 1
			table.insert(groupItems, {title = groupName, value = count})
		end
		
		propertyTable:addObserver( 'presetGroup', 
		function( properties, key, newValue )
			properties.preset = 1
			groupPresets = nil
			if newValue >= 2 then
				groupPresets = g_MPExtrasPluginAppName_presets[newValue - 1]
			end
			if groupPresets == nil then
				properties.hide = false
			end
		end )

		if count > 0 then
			result = {
				{
					title = 'MPExtrasAppName Batch Processing',

					viewFactory:row {
						viewFactory: static_text {
							title = LOC( "$$$/MPExtrasPluginAppName/Export/Group=Group:" ),
						},
						viewFactory:popup_menu {
							value = LrView.bind('presetGroup'),
							items = groupItems,
							width_in_chars = 15,
						},
					
						viewFactory: static_text {
							title = LOC( "$$$/MPExtrasPluginAppName/Export/Preset=Preset:" ),
						},
						viewFactory:popup_menu {
							value = LrView.bind('preset'),
							items = LrView.bind(
							{
								key = 'presetGroup', 
								transform = function(value, fromTable)
									if not fromTable then
										return LrBinding.kUnsupportedDirection
									end
									local presetItems = {}
									local presets = g_MPExtrasPluginAppName_presets
									local groupPresets = nil
									if value >= 2 then
										groupPresets = presets[value - 1]
									end
									if groupPresets ~= nil then
										for index, preset in pairs(groupPresets) do
											table.insert(presetItems, {title = preset.name, value = index})
										end
									else
										table.insert(presetItems, {title = "", value = 1})
									end
									return presetItems
								end
							}),
							enabled = LrView.bind(
							{
								key = 'presetGroup', 
								transform = function(value, fromTable)
									if not fromTable then
										return LrBinding.kUnsupportedDirection
									end
									local result = false
									if value >= 2 then
										result = g_MPExtrasPluginAppName_presets[value - 1] ~= nil
									end
									return result
								end
							}),
						
							width_in_chars = 15,
						},
					},
				
					viewFactory:row {
						spacing = viewFactory:control_spacing(),
						viewFactory:checkbox {
							title = LOC( "$$$/MPExtrasPluginAppName/Export/HideWindow=Hide MPExtrasAppName window" ),
							value = LrView.bind('hide'),
							enabled = LrView.bind(
							{
								key = 'presetGroup', 
								transform = function(value, fromTable)
									if not fromTable then
										return LrBinding.kUnsupportedDirection
									end
									local result = false
									if value >= 2 then
										result = g_MPExtrasPluginAppName_presets[value - 1] ~= nil
									end
									return result
								end
							}),
						},
					},
				}
			}
		end
	end
	return result
end

return ExportProcessRenderedPhotos
