local SCRIPT_TITLE = 'Translate scripts V1.0'

--[[

Synthesizer V Studio Pro Script
 
lua file name: TranslateScripts.lua

Retrieving all SV:T(text) found inside a script
and generate a getTranslations function 
with all text found into the clipboard

Set askForScriptFile = true to display an input box
	if false variable "scriptFile" is used, set your .lua file below (class "NotesObject")
Set isMultipleScript = true to loop all files into subfolders
	note: if true askForScriptFile is not used
Set	isFilterSubfolder = true to filter a specific subfolder
	mode used only if isMultipleScript = true
	to specify the filtered subfolder update the variable: filterSubfolder

Note: Not tested in the MACOS env.

Update: Get file path from clipboard if exists
		Notes count issue
		5 - Add case if no getTranslations() exists

2025 - JF AVILES
--]]

-- Generated by JFA TranslateScripts.lua
function getTranslations(langCode)
	return getArrayLanguageStrings()[langCode]
end

-- Generated by JFA TranslateScripts.lua
function getArrayLanguageStrings()
	return {
		["en-us"] = {
			{"No such file or directory", "No such file or directory"},
			{"Enter the full path filename", "Enter the full path filename"},
			{"Cannot find automatically the script path. Please insert the full path here:", "Cannot find automatically the script path. Please insert the full path here:"},
			{"Cannot find user profile. Please insert the full path here:", "Cannot find user profile. Please insert the full path here:"},
			{"Cannot find automatically the script folder path. Please insert the folder path here:", "Cannot find automatically the script folder path. Please insert the folder path here:"},
			{"Generated by", "Generated by"},
			{"TranslateScripts.lua", "TranslateScripts.lua"},
			{"Unable to open file:", "Unable to open file:"},
			{"Unable to save file:", "Unable to save file:"},
			{"Nothing to read!", "Nothing to read!"},
			{"Done!", "Done!"},
			{"Source code copied into the clipboard!", "Source code copied into the clipboard!"},
			{"No file found!", "No file found!"},
			{"Source code created into new files!", "Source code created into new files!"},
			{"not found!", "not found!"},
		},
	}
end

function getClientInfo()
	return {
		name = SV:T(SCRIPT_TITLE),
		category = "_JFA_Tools",
		author = "JFAVILES",
		versionNumber = 5,
		minEditorVersion = 65540
	}
end

-- Define a class "NotesObject"
NotesObject = {
	project = nil,
	initialAuthor = "JFA",
	scriptFile = "Utilities/RandomizeParameters.lua",
	isCreateNewFiles = true,	-- True => Create a new file (newFileExtension) with language code replaced
	fileExtension= ".lua", 
	newFileExtension = "-trad.lua",
	isClipboardActived = true,	-- get file path from clipboard if present
	askForScriptFile = true,	-- if true a dialog box is displayed
	isMultipleScript = false,	-- if true askForScriptFile is not more used
	isFilterSubfolder = false,
	filterSubfolder = "Utilities", -- filter for multiple subfolders scan
	winSepCharPath = "/",
	winScriptPathBegin = "OneDrive", -- C:\Users\YOUR_USER_NAME\OneDrive\Documents\Dreamtonics\Synthesizer V Studio 2\Script
	winScriptPathDocument = "Documents", -- "\\Documenti", etc.
	winScriptPathEnd = "/Dreamtonics/Synthesizer V Studio 2/scripts/",
	macosPath = "/Library/Application Support/Dreamtonics/Synthesizer V Studio 2/Script/",
	hostinfo = nil,
	osType = "",
	osName = "",
	hostName = "",
	languageCode = "", 
	hostVersion = "",
	hostVersionNumber = 0
}

-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
    self.project = SV:getProject()
	self:getHostInformations()
	
    return self
end

-- Show message dialog
function NotesObject:show(message)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), message)
end

-- Get host informations
function NotesObject:getHostInformations()
	self.hostinfo = SV:getHostInfo()
	self.osType = self.hostinfo.osType  -- "macOS", "Linux", "Unknown", "Windows"
	self.osName = self.hostinfo.osName
	self.hostName = self.hostinfo.hostName
	self.languageCode = self.hostinfo.languageCode
	self.hostVersion = self.hostinfo.hostVersion
	self.hostVersionNumber = self.hostinfo.hostVersionNumber
end

-- Read file content
function NotesObject:readAll(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
end

-- Check if file exists
function NotesObject:isFileExists(fileName)
	local result = false
	local file = io.open(fileName, "r")
	if file ~= nil then
		io.close(file)
		result = true
	end
	return result
end

-- Get windows user profile
function NotesObject:getWindowsUserProfile()
	local userProfile = os.getenv("USERPROFILE")
	userProfile = string.gsub(userProfile,"\\","/")
	userProfile = string.gsub(userProfile,"//","/")	
	return userProfile
end

-- Check if folder exists
function NotesObject:isFolderExists(folderName)
  local fileHandle, error = io.open(folderName .. "/*.*", "r")
  if fileHandle ~= nil then
    io.close(fileHandle)
    return true
  else
	-- be carefull! Text returned by os system
    if string.match(error, SV:T("No such file or directory")) then
      return false
    else
      return true
    end
  end
end

-- Split string by sep char
function NotesObject:split(str, sep)
   local result = {}
   local regex = ("([^%s]+)"):format(sep)
   for each in str:gmatch(regex) do
	  table.insert(result, each)
   end
   return result
end

-- Read text file
function NotesObject:readTextFile(file)
	local arr = {}
	local err = false
	local handle, errMessage = io.open(file,"r")
	if handle then
		local value = handle:read("*line")
		while value do
			table.insert(arr, value)
			value = handle:read("*line")
		end
		handle:close()
	else
		err = true
	end
  return arr, err, errMessage
end

-- Get clean filename
function NotesObject:getCleanFilename(file)
	local filename = file
	if #filename > 0 then
		if string.find(filename, '"') ~= nil then
			filename = filename:gsub('"', '')
		end
	end
	return filename
end

-- Get filename only
function NotesObject:getFileNameOnly(file)
	return file:match("^.+\\(.+)$")
end

-- Get folder path
function NotesObject:getPath(file)
	return file:match("(.*[/\\])")
end

-- Get wave file path
function NotesObject:getScriptFile()
	local filename = SV:showInputBox(SV:T(SCRIPT_TITLE), SV:T("Enter the full path filename"), "")
	return filename
end

-- Get file path
function NotesObject:getFilePath()	
	local scriptFilePath = ""
	local scriptFolder = ""
	local scriptErrorText = SV:T("Cannot find automatically the script path. Please insert the full path here:")
	local scriptErrorUserProfileText = SV:T("Cannot find user profile. Please insert the full path here:")
	
	if self.osType ~= "Windows" then	
		-- "macOS", "Linux", "Unknown"
		scriptFilePath = self.macosPath .. self.scriptFile
		if not self:isFileExists(scriptFilePath) then
			scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorText, scriptFilePath)
		end
	else
		-- Windows
		local userProfile = self:getWindowsUserProfile()
		if userProfile then
			-- if direct
			scriptFolder = userProfile .. self.winSepCharPath .. self.winScriptPathDocument 
							.. self.winScriptPathEnd
			scriptFilePath = scriptFolder .. self.scriptFile				
			if not self:isFileExists(scriptFilePath) then
				-- trying with adding OneDrive
				scriptFolder = userProfile 
								.. self.winSepCharPath 
								.. self.winScriptPathBegin 
								.. self.winSepCharPath 
								.. self.winScriptPathDocument
								.. self.winScriptPathEnd
				scriptFilePath = scriptFolder .. self.scriptFile			
				if not self:isFileExists(scriptFilePath) then
					scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorText, scriptFilePath)
				end
			end
		else
			scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorUserProfileText, "")
		end
	end
	return scriptFilePath
end

-- Get Scripts path
function NotesObject:getScriptsPath()
	local scriptFilePath = ""
	local scriptFolder = ""
	local scriptErrorText = SV:T("Cannot find automatically the script folder path. Please insert the folder path here:")
	local scriptErrorUserProfileText = SV:T("Cannot find user profile. Please insert the full path here:")
	
	if self.osType ~= "Windows" then	
		-- "macOS", "Linux", "Unknown"
		scriptFilePath = self.macosPath
		if not self:isFolderExists(scriptFilePath) then
			scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorText, scriptFilePath)
		end
	else
		-- Windows
		local userProfile = self:getWindowsUserProfile()
		if userProfile then
			-- if direct
			scriptFolder = userProfile .. self.winSepCharPath .. self.winScriptPathDocument 
							.. self.winScriptPathEnd
			scriptFilePath = scriptFolder
			if not self:isFolderExists(scriptFilePath) then
				-- trying with adding OneDrive
				scriptFolder = userProfile 
								.. self.winSepCharPath 
								.. self.winScriptPathBegin 
								.. self.winSepCharPath 
								.. self.winScriptPathDocument
								.. self.winScriptPathEnd
				scriptFilePath = scriptFolder
				if not self:isFolderExists(scriptFilePath) then
					scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorText, scriptFilePath)
				end
			end
		else
			scriptFilePath = SV:showInputBox(SV:T(SCRIPT_TITLE), scriptErrorUserProfileText, "")
		end
	end
	return scriptFilePath
end

-- Get source code
function NotesObject:getSourceCode(languageCode, textArray)
	local fTranslations = ""
	local fLanguage = ""
	local authorComment = "-- " .. SV:T("Generated by") .. " " .. self.initialAuthor .. " " .. SV:T("TranslateScripts.lua")
	
	fTranslations = fTranslations .. authorComment .. "\n"
	fTranslations = fTranslations .. "function getTranslations(langCode)" .. "\n"
	fTranslations = fTranslations .. "\t".. "return getArrayLanguageStrings()[langCode]" .. "\n"
	fTranslations = fTranslations .. "end" .. "\n"
	
	fLanguage = fLanguage .. authorComment .. "\n"
	fLanguage = fLanguage .. "function getArrayLanguageStrings()" .. "\n"
	fLanguage = fLanguage .. "\t" .. "return {" .. "\n"
	fLanguage = fLanguage .. '\t\t["' .. languageCode .. '"] = {' .. "\n"
	for iItem = 1, #textArray do
		fLanguage = fLanguage .. '\t\t\t{"' .. textArray[iItem] .. '", "' .. textArray[iItem] .. '"},' .. "\n"
	end
	fLanguage = fLanguage .. "\t\t}," .. "\n"
	fLanguage = fLanguage .. "\t}" .. "\n"
	fLanguage = fLanguage .. "end" .. "\n"
	
	return fTranslations .. "\n" .. fLanguage
end

-- Is text already exists in array
function NotesObject:isTextExists(text, textArray)
	local exists = false
	for iPos = 1, #textArray do
		if textArray[iPos] == text then
			exists = true
			break
		end
	end
	return exists
end

-- Get separator path char
function NotesObject:getSepPathChar()
	local sepPath = "/"
	-- check if it's a subfolder
	if self.osType ~= "Windows" then	
		sepPath = "/"
	end
	return sepPath
end

-- List files in folder
function NotesObject:listFiles(directory)
    local i, dir, popen = 0, {}, io.popen
	local full_dir = {}
    local pfile
	
	if self.osType ~= "Windows" then
		local tempfilename = os.tmpname()
		os.execute([[ls -d ]] .. directory .. [[*/ >> ]] .. tempfilename)
		
		if self:isFileExists(tempfilename) then
			pfile = lines_from(tempfilename)
			os.remove(tempfilename)
			
			for _,foldername in pairs(pfile) do
				local testname = string.lower(foldername)
				if string.find(testname,"ignore") == nil then
					if string.find(testname, self.fileExtension, 1, true) ~= nil then
						foldername = string.gsub(foldername,"//","/")
						i = i + 1
						full_dir[i] = foldername
						local start = 0, searchnew, searchold
						
						while true do
						  start = string.find(foldername, "/", start+1)    -- find 'next' newline
						  if start == nil then break end
						  searchold = searchnew
						  searchnew = start
						end
						dir[i] = string.sub(foldername,searchold+1)		
						dir[i] = string.gsub(dir[i],"/","")
					end
					-- Check if it's a subfolder
					if string.find(testname, self.fileExtension, 1, true) == nil and 
						string.find(testname, ".js", 1, true) == nil  and
						string.find(testname, ".txt", 1, true) == nil then
						local subfolder = directory .. testname .. self:getSepPathChar()
						local dir2, full_dir2 = self:listFiles(subfolder)
						if #full_dir2 > 0 then
							for k, filePath in pairs(full_dir2) do
								table.insert(dir, dir2[k])
								table.insert(full_dir, filePath)
							end
						end
					end
					
				end	
			end
		end	
	else
		local cmd = 'dir "'..directory..'" /b'		
		pfile = popen(cmd)
		for filename in pfile:lines() do
			local testname = string.lower(filename)
			if string.find(testname,"ignore") == nil then
				if string.find(testname, self.fileExtension, 1, true) ~= nil then
					i = i + 1
					dir[i] = filename
					full_dir[i] = directory .. filename		
				end
				-- Check if it's a subfolder
				if string.find(testname, ".", 1, true) == nil then
					local subfolder = directory .. testname .. self:getSepPathChar()
					local dir2, full_dir2 = self:listFiles(subfolder)
					if #full_dir2 > 0 then
						for k, filePath in pairs(full_dir2) do
							table.insert(dir, dir2[k])
							table.insert(full_dir, filePath)
						end
					end
				end
			end			
		end
		pfile:close()
		
	end	
    return dir, full_dir
end

-- file processing
function NotesObject:fileProcess(file, languageCode)
	-- Process one file
	local textFound = {}
	local scriptLines = {}
	local newScriptLines = {}
	local languageSourceCode = ""
	local firstFunction = "function getTranslations(langCode)"
	local functionEnd = "end"
	local secondFunction = "function getArrayLanguageStrings()"
	local functionComment = "-- " .. SV:T("Generated by") .. " " .. self.initialAuthor .. " " .. SV:T("TranslateScripts.lua")
	local baseFunction = "function getClientInfo()"
	local firstFunctionPosBegin = 0
	local firstFunctionPosEnd = 0
	local secondFunctionPosBegin = 0
	local secondFunctionPosEnd = 0
	local firstFunctionCommentPos = 0
	local secondFunctionCommentPos = 0
	local baseFunctionPosBegin = 0
	local baseFunctionPosEnd = 0

	local scriptLines, err, errMessage = self:readTextFile(file)
	if err then
		self:show(SV:T("Unable to open file:") .. "\r" .. errMessage)
	else
		for iPos = 1, #scriptLines do
			local line = scriptLines[iPos]

			if line == baseFunction then
				baseFunctionPosBegin = iPos
			end
			if baseFunctionPosBegin > 0 and baseFunctionPosEnd == 0 then
				if line == functionEnd then
					baseFunctionPosEnd = iPos
				end
			end
			if line == firstFunction then
				firstFunctionPosBegin = iPos
			end
			if firstFunctionPosBegin > 0 and firstFunctionPosEnd == 0 then
				if line == functionEnd then
					firstFunctionPosEnd = iPos
				end
			end
			if line == secondFunction then
				secondFunctionPosBegin = iPos
			end
			if secondFunctionPosBegin > 0 and secondFunctionPosEnd == 0 then
				if line == functionEnd then
					secondFunctionPosEnd = iPos
				end
			end
			if line == functionComment and firstFunctionCommentPos == 0 then
				firstFunctionCommentPos = iPos
			end
			if line == functionComment and firstFunctionCommentPos > 0 
				and secondFunctionCommentPos == 0 then
				secondFunctionCommentPos = iPos
			end

			for capture in string.gmatch(line, 'SV%:T%("(.-)"%)') do
				if capture ~= "SCRIPT_TITLE" then
					if not self:isTextExists(capture, textFound) then
						table.insert(textFound, capture)
					end
				end
			end						
		end
		
		-- Get text without current language translate
		for iPos = 1, #scriptLines do
			local line = scriptLines[iPos]
			local addLine = true

			if iPos == firstFunctionCommentPos or 
				iPos == secondFunctionComment then
				addLine = false
			end
			if secondFunctionPosBegin > 0 then
				if iPos >= firstFunctionPosBegin and iPos <= secondFunctionPosEnd + 1 then
					addLine = false
				end
			else
				if iPos >= firstFunctionPosBegin and iPos <= firstFunctionPosEnd + 1 then
					addLine = false
				end
			end

			if addLine then 
				table.insert(newScriptLines, line)
			end
		end
		-- Get new language code
		languageSourceCode = self:getSourceCode(languageCode, textFound)

		-- self:show("newScriptLines: " .. #newScriptLines 
		-- .. ", scriptLines: " .. #scriptLines
		-- .. ", firstFunctionCommentPos: " .. firstFunctionCommentPos
		-- .. ", firstFunctionPosBegin: " .. firstFunctionPosBegin
		-- .. ", secondFunctionPosBegin: " .. secondFunctionPosBegin
		-- .. ", secondFunctionPosEnd: " .. secondFunctionPosEnd)
		
		-- Get new lines for a target file with new language code replaced
		if #newScriptLines > firstFunctionPosBegin then
			if firstFunctionCommentPos > 0 then
				table.insert(newScriptLines, firstFunctionCommentPos, languageSourceCode)
			else
				if firstFunctionPosBegin == 0 then
					table.insert(newScriptLines, baseFunctionPosEnd + 1, languageSourceCode)
				else
					table.insert(newScriptLines, firstFunctionPosBegin, languageSourceCode)
				end
			end
		end
	end
	return languageSourceCode, newScriptLines
end

-- Get lua file path from clipboard
function NotesObject:getFilesFromClipboard()
	local contentInfo = SV:getHostClipboard()
	local files = {}
	
	if contentInfo ~= nil and type(contentInfo) == "string" then
		-- Get file name from last clipboard
		if string.find(contentInfo, self.fileExtension, 1, true) ~= nil then
			-- Check if multiple files
			if string.find(contentInfo, "\r", 1, true) ~= nil then
				self.isMultipleScript = true
			else
				self.isMultipleScript = false
			end

			local filesInLine = self:split(contentInfo, "\r\n")
			for i, file in ipairs(filesInLine) do
				local fileClean = self:getCleanFilename(file)
				if self:isFileExists(fileClean) then
					table.insert(files, fileClean)
				end
			end			
		end
	end
	return files
end

-- Save text file
function NotesObject:saveTextFile(text, filename)
	local fo, errMessage = io.open(filename, "w")
	if fo then
	  fo:write(text)
	  fo:close()
	else
	  self:show(SV:T("Unable to save file:") .. "\r" .. errMessage)
	end
end

-- Start project notes processing
function NotesObject:start()
	local result = false
	-- self:show(" osType: " .. self.osType .. "\r"
	-- .. " osName: " .. self.osName .. "\r"
	-- .. " hostName: " .. self.hostName .. "\r"
	-- .. " languageCode: " .. self.languageCode .. "\r"
	-- .. " hostVersion: " .. self.hostVersion .. "\r" )
	
	if self.isMultipleScript then
		local folderPath = self:getScriptsPath()
		
		if folderPath ~= nil and #folderPath > 0 then
			local filter = ""
			if self.isFilterSubfolder then
				filter = self.filterSubfolder .. self:getSepPathChar()
			end
			local pathFolder = folderPath .. filter
			
			folderlist, full_folderlist = self:listFiles(pathFolder)
			local filesPathList = {}
			local filesList = {}
			local languageSourceCode = ""
			
			for k, filePath in pairs(full_folderlist) do
				-- Only lua scripting files
				if string.find(full_folderlist[k], self.fileExtension, 1, true) ~= nil then
					table.insert(filesPathList, filePath)
					table.insert(filesList, folderlist[k])

					local newFileSourceCode, newScriptLines = self:fileProcess(filePath, self.languageCode)
					if newFileSourceCode ~= nil and #newFileSourceCode > 0 then
						languageSourceCode = languageSourceCode
							.. filePath .. "\r"
							.. newFileSourceCode
							.. "\r"
					else
						languageSourceCode = languageSourceCode
							.. filePath .. "\r"
							.. SV:T("Nothing to read!")
							.. "\r"
					end					
				end
			end
			SV:setHostClipboard(languageSourceCode)
			self:show(SV:T("Done!") 
				.. "\r" .. SV:T("Source code copied into the clipboard!"))
			
			-- self:show("filesPathList:\r" .. table.concat(filesPathList, "\r"))
			-- self:show("filesList:\r" .. table.concat(filesList, "\r"))
		else
			self:show(SV:T("No file found!"))
		end
	else
		local files = {}
		if self.isClipboardActived then
			files = self:getFilesFromClipboard()
		end
		
		-- files exists in clipboard
		if #files > 0 then
			local countStrings = 0
			local languageSourceCode = ""
			local filenames = ""
			for i, file in ipairs(files) do
				local newFileSourceCode, newScriptLines = self:fileProcess(file, self.languageCode)
				local fileInfos = ""
				if newFileSourceCode ~= nil and #newFileSourceCode > 0 then
					if #files > 1 then
						fileInfos = file .. "\r"
					end
					languageSourceCode = languageSourceCode
						.. fileInfos
						.. newFileSourceCode
						.. "\r"
				else
					if #files > 1 then
						fileInfos = file .. "\r"
					end
					languageSourceCode = languageSourceCode
						.. fileInfos
						.. SV:T("Nothing to read!")
						.. "\r"
				end					
				countStrings = countStrings + #newFileSourceCode
				
				if self.isCreateNewFiles then
					local filename = string.gsub(file, self.fileExtension, self.newFileExtension)
					local newFileContent = table.concat(newScriptLines, "\n")
					self:saveTextFile(newFileContent, filename)
					filenames = filenames .. self:getFileNameOnly(filename) .. "\r"
				else
					filenames = filenames .. self:getFileNameOnly(file) .. "\r"
				end
			end
			if countStrings > 0 then
				if self.isCreateNewFiles then
					self:show(SV:T("Done!") .. "\r"
						.. filenames
						.. "\r" .. SV:T("Source code created into new files!"))
				else
					SV:setHostClipboard(languageSourceCode)
					self:show(SV:T("Done!") .. "\r"
						.. filenames
						.. "\r" .. SV:T("Source code copied into the clipboard!"))
				end
			else
				self:show(SV:T("Nothing to read!"))
			end
		else
			local filename = ""
			if self.askForScriptFile then
				filename = self:getScriptFile()
				if #filename == 0 then
					return result
				end
				
				filename = self:getCleanFilename(filename)
				self.scriptFile = filename
			else
				filename = self:getFilePath()
				if #filename == 0 then
					return result
				end
				filename = self:getCleanFilename(filename)
				self.scriptFile = filename
			end
			
			-- if process not ok
			if not self:isFileExists(self.scriptFile) then
				self:show(self.scriptFile .. " " .. SV:T("not found!"))
			else
				local languageSourceCode, newScriptLines = self:fileProcess(self.scriptFile, self.languageCode)
				
				if languageSourceCode ~= nil and #languageSourceCode > 0 then
					SV:setHostClipboard(languageSourceCode)
					self:show(SV:T("Done!") 
						.. "\r" .. SV:T("Source code copied into the clipboard!"))
				else
					self:show(SV:T("Nothing to read!"))
				end
			end
		end
	end
	return result
end

-- Main process
function main(notEndProcess)
	local notesObject = NotesObject:new()
	
	notesObject:start()
	
	if notEndProcess == nil then
		-- End of script
		SV:finish()
	end
end