--------------------------------------------------
---  Copyright 2008-2017, HDRsoft - www.hdrsoft.com
--------------------------------------------------

--local LrApplication = import 'LrApplication'
local LrDialogs = import 'LrDialogs'
local LrErrors = import 'LrErrors'
local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'
local LrDate = import 'LrDate'
local LrTasks = import 'LrTasks'
local prefs = import 'LrPrefs'.prefsForPlugin() 
local LrLogger = import 'LrLogger'

local compatibleVersion='6.0'

local myLogger = LrLogger('PhotomatixLogger')
myLogger:enable("print") 


PhotomatixApp = {}

function PhotomatixApp.outputToLog(message)
	myLogger:trace(message)
end

function PhotomatixApp.clientExists (appPath, isDirectPathToClient)
	local pathContents="Contents"
	local pathRes="Resources"
	local pathClient="PhotomatixClient"
	local doesExists=false

    if (MAC_ENV) then

-- gj170318 before checking the existence/validity of the PhotomatixClient command line app, we first make sure that the path checked comes from PMP 6
        local pmpPath=appPath
        PhotomatixApp.outputToLog(string.format('PhotomatixApp.clientExists: %s', appPath))
        if isDirectPathToClient then
            pmpPath=LrPathUtils.parent(pmpPath)
            pmpPath=LrPathUtils.parent(pmpPath)
            pmpPath=LrPathUtils.parent(pmpPath)
        end
        if (LrFileUtils.exists(pmpPath)) then
            local pmpFile=LrPathUtils.leafName(pmpPath)
            PhotomatixApp.outputToLog(string.format('PMP File: %s', pmpFile))
            if ((pmpFile == "Photomatix Pro 5.app") or (pmpPath == "Photomatix Pro.app")) then
                return false
            end
        end
-- gj170318end

		if not isDirectPathToClient then 
			appPath=LrPathUtils.child (appPath, pathContents) 
		end	
		doesExist=LrFileUtils.exists(appPath) 
		if doesExist then
			if not isDirectPathToClient then 
				appPath=LrPathUtils.child (appPath, pathRes) 
				doesExist=LrFileUtils.exists(appPath) 
			end
			if doesExist then
				if not isDirectPathToClient then 
					appPath=LrPathUtils.child (appPath, pathClient) 
					doesExist=LrFileUtils.exists(appPath) 
				end
				if doesExist then
					PhotomatixApp.outputToLog(string.format('%s exists', appPath))
					doesExist=false  -- re-initialisatin of doesExist as we now need to check that PhotomatixClient is the right version
					local fileAtt=LrFileUtils.fileAttributes(appPath)
					if (fileAtt.fileModificationDate~=nil) then
						PhotomatixApp.outputToLog(string.format('file modification date: %d', fileAtt.fileModificationDate))
					--	if (fileAtt.fileModificationDate>293978554) then  -- 293978554 is the creation/modification date of PhotomatixClient part of Photomatix Pro 3.2.9
					--	if (fileAtt.fileModificationDate>311771938) then  -- 311771938 is the creation/modification date of PhotomatixClient part of Photomatix Pro 4.0.2 the last version before 4.1
						if (fileAtt.fileModificationDate>=399545514) then  -- 399545514 is the creation/modification date of PhotomatixClient part of Photomatix Pro 5.0beta1

                            PhotomatixApp.outputToLog(string.format('about to set doesExist to appPath: %s', appPath))

							doesExist=appPath
						end
					else 
						doesExist=appPath
					end
				else
					PhotomatixApp.outputToLog(string.format('%s not found', appPath))	
				end
			end
		end
	else  -- Windows
		pathClient="PhotomatixClient.exe"
		appPath=LrPathUtils.parent(appPath)
		appPath=LrPathUtils.child (appPath, pathClient) 
		doesExist=LrFileUtils.exists(appPath) 
		if doesExist then
			doesExist=false  -- re-initialisatin of doesExist as we now need to check that PhotomatixClient is the right version
			local sysTempPath = LrPathUtils.getStandardFilePath('temp')
			local now = LrDate.currentTime()
			tempFile = LrPathUtils.child(sysTempPath, LrDate.timeToUserFormat(now, 'temp_lrexport2photomatix_%m%d%H%M%S_output'))
			local PhotomatixClientCommand=string.format('\"%s\" -V > \"%s\"', appPath, tempFile)
            PhotomatixClientCommand=string.format('\"%s\"', PhotomatixClientCommand)

			local retour=LrTasks.execute(PhotomatixClientCommand)
			PhotomatixApp.outputToLog(PhotomatixClientCommand)
			local outputMessage
			local handle = io.open(tempFile, 'rb')
			if handle then
				PhotomatixApp.outputToLog("Handle ok")
				outputMessage = handle:read('*a')
               		handle:close()
			end
			LrFileUtils.delete(tempFile)

			if outputMessage == nil then
				outputMessage = "???"
			end			 
			PhotomatixApp.outputToLog(outputMessage)
			local formattedMsg = string.format(outputMessage)
			if string.match(formattedMsg, string.format('^%s',compatibleVersion)) then
				doesExist=appPath
				PhotomatixApp.outputToLog(string.format('%s exists and has correct version', appPath))
			else
				PhotomatixApp.outputToLog(string.format('%s exists but has incorrect version', appPath))
			end
		else
			PhotomatixApp.outputToLog(string.format('%s NOT found', appPath))	
		end
	end

    PhotomatixApp.outputToLog(string.format('about to return with: %s', doesExist))

	return doesExist
end


function PhotomatixApp.getPath( )
	local appPath=""
	local doesExist=false

	local debug=false
	
	local path1="Program Files"
	local path2="PhotomatixPro6"
	local path3="PhotomatixClient.exe"
		
	if (MAC_ENV) then
		path1="/Applications"
		path3="Photomatix Pro 6.app"
		local desktopPath=LrPathUtils.getStandardFilePath('desktop') 

		local folderPath=nil		

--on regarde si Photomatix Pro est directement sous Applications
		appPath = LrPathUtils.child (path1, path3) 
		doesExist=LrFileUtils.exists(appPath) 		
		if doesExist then
			if (debug) then
				PhotomatixApp.outputToLog(string.format('getPath - LrFileUtils.exists returned false for: %s ', appPath))			
			end
			doesExist=PhotomatixApp.clientExists(appPath, false)
			if (debug) then
				PhotomatixApp.outputToLog(string.format('getPath - PhotomatixClient doesExist retour: %s ', doesExist))			
			end
			if doesExist then
				appPath=doesExist
				if (debug) then
					PhotomatixApp.outputToLog(string.format('PhotomatixClient found in Applications %s ', appPath))			
				end
			end
		end
		if not doesExist then
			if (debug) then
				PhotomatixApp.outputToLog(string.format('getPath - LrFileUtils.exists returned true for: %s ', appPath))			
			end
--on regarde si Photomatix Pro est directement sous Desktop
			appPath = LrPathUtils.child (desktopPath, path3) 
			doesExist=LrFileUtils.exists(appPath) 		
			if doesExist then
				doesExist=PhotomatixApp.clientExists(appPath, false)
				if doesExist then
					appPath=doesExist
				end
			end
		end

--quand non directement sous Applications ou Desktop, on essaie de trouver le dossier contenant Photomatix Pro 

		if not doesExist then
--recherche du dossier contentant Photomatix Pro sous Applications et Desktop

			local possibleFolders = {}
			local nPossible=0
			local appName="PhotomatixPro6"

			for versionMinor=3, 0, -1 do
--				if versionMinor > 1 then
					table.insert(possibleFolders, string.format('%s.%d',appName,versionMinor))
					PhotomatixApp.outputToLog(string.format('%d:  %s.%d',nPossible,appName,versionMinor))
--				end
				nPossible=nPossible+1
--				PhotomatixApp.outputToLog(versionMinor)
				for versionRev=10, 1, -1 do
					table.insert(possibleFolders, string.format('%s.%d.%d',appName,versionMinor,versionRev))
--					PhotomatixApp.outputToLog(string.format('%d:  %s.%d.%d',nPossible,appName,versionMinor,versionRev))
					nPossible=nPossible+1
				end
			end

			for iEssai = 1, nPossible-1, 1 do
--				PhotomatixApp.outputToLog(string.format('essai %d:  %s',iEssai,possibleFolders[iEssai]))
				folderPath = LrPathUtils.child (path1, possibleFolders[iEssai]) 
--				PhotomatixApp.outputToLog(folderPath)
				doesExist = LrFileUtils.exists(folderPath)
				if not doesExist then
					folderPath = LrPathUtils.child (desktopPath, possibleFolders[iEssai]) 
--					if iEssai>(nPossible-5) then
--						PhotomatixApp.outputToLog(string.format('Trying to find Photomatix Pro under folder %s ', folderPath))			
--					end
					doesExist = LrFileUtils.exists(folderPath)					
				end				
				if doesExist then break end
			end
		end
			
		if doesExist then
			if (folderPath) then
--				PhotomatixApp.outputToLog(string.format('folderPath found: %s ', folderPath))			
--				PhotomatixApp.outputToLog(string.format('path3: %s ', path3))			
				appPath = LrPathUtils.child (folderPath, path3) 
				doesExist=LrFileUtils.exists(appPath) 		
				if doesExist then
					doesExist=PhotomatixApp.clientExists(appPath, false)
					if doesExist then
						appPath=doesExist
					end
				end
			end
			doesExist=LrFileUtils.exists(appPath) 		
		end		
			
	else  -- Windows
		local appPrefPath=LrPathUtils.getStandardFilePath('appPrefs') 

		if string.len(appPrefPath)>5 then
			local racine = string.sub (appPrefPath, 0, 2)
			appPath = LrPathUtils.child (racine, path1) 
			appPath = LrPathUtils.child (appPath, path2) 
			appPath = LrPathUtils.child (appPath, path3) 
			doesExist=PhotomatixApp.clientExists(appPath, false)
		end
	end	
	
	
	if not doesExist then
		local savedAppPath=prefs.photomatix4Path
		if savedAppPath and not string.find(savedAppPath, "PhotomatixPro4") then
			doesExist=LrFileUtils.exists(savedAppPath) 
			if doesExist then
				local clientName="PhotomatixClient.exe"
				if (MAC_ENV) then 
					clientName="PhotomatixClient"
				end	
				if LrPathUtils.leafName(savedAppPath)==clientName then
					doesExist=true	
					appPath=savedAppPath
--					PhotomatixApp.outputToLog(string.format('savedAppPath taken - %s ', savedAppPath))			
				end
			end
		end 
	end
	

	while not doesExist do
		local selectedPathArray={}
		local dialogMessage = LOC "$$$/Photomatix/FindingPhotomatixApp/Error/Incompatible/Message/Mac=If you have installed Photomatix Pro 6.0 or higher on your computer, click on 'Browse' to select the 'Photomatix Pro.app' file.^nOtherwise, please download the latest version of Photomatix Pro from www.HDRsoft.com."
		local dialogTitle = LOC "$$$/Photomatix/FindingPhotomatixApp/Error/Incompatible/Title/Mac=Could not find Photomatix Pro application compatible with this Plugin"
		
		if (WIN_ENV) then 
			dialogMessage = LOC "$$$/Photomatix/FindingPhotomatixApp/Error/Incompatible/Message/Win=If you have installed Photomatix Pro 6.0 or higher on your computer, click on 'Browse' to select the 'PhotomatixPro.exe' file located in the folder where you installed Photomatix Pro.^nOtherwise, please download the latest version of Photomatix Pro from www.HDRsoft.com."
			dialogTitle = LOC "$$$/Photomatix/FindingPhotomatixApp/Error/Incompatible/Title/Win=Could not find Photomatix Pro program compatible with this Plugin"
		end
		
		local conf2 = LrDialogs.confirm(dialogTitle, dialogMessage, LOC "$$$/Photomatix/General/Browse=Browse",  LOC "$$$/Photomatix/General/Cancel=Cancel" )
		if conf2 == 'cancel' then
			if (debug) then
				PhotomatixApp.outputToLog('getPath - user selected Cancel')			
			end
			return
		end
		if (MAC_ENV) then 
			selectedPathArray = LrDialogs.runOpenPanel (
				{
				title = LOC "$$$/Photomatix/FindingPhotomatixApp/BrowseTo/Mac=Browse to Photomatix Pro (file Photomatix Pro.app)",
				prompt = "Select",
				canChooseFiles = true,
				canChooseDirectories = false,
				canCreateDirectories = false,
				allowsMultipleSelection = false,
				}
			)
		else
			selectedPathArray = LrDialogs.runOpenPanel (
				{
				title = LOC "$$$/Photomatix/FindingPhotomatixApp/BrowseTo/Win=Browse to Photomatix Pro (file PhotomatixPro.exe)",
				prompt = "Select",
				canChooseFiles = true,
				canChooseDirectories = false,
				canCreateDirectories = false,
				allowsMultipleSelection = false,
				fileTypes = "exe",
				}
			)
		end
		if selectedPathArray == nil then
			PhotomatixApp.outputToLog("selectedPathArray is nil")
			return
		end
		local selectedPath=selectedPathArray[1];
		doesExist=PhotomatixApp.clientExists(selectedPath, false)
		if doesExist then
			appPath=doesExist	
		else
			LrDialogs.message(LOC "$$$/Photomatix/General/Error=Error", LOC "$$$/Photomatix/FindingPhotomatixApp/Error/Selected=The selected file does not seem to be Photomatix Pro version 6 or higher", "info")
			return
		end
	end	
	
	prefs.photomatix4Path=appPath
end
