local SCRIPT_TITLE = 'Group phonemes V1.0'

--[[

lua file name: GroupPhonemes.lua

Get group phonemes and user updated data

Working only with SynthV >= 2.1.1

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 group selected found!", "No group selected found!"},
			{"Note", "Note"},
			{"lyrics", "lyrics"},
			{"position", "position"},
			{"activity", "activity"},
			{"strength", "strength"},
			{"Updated", "Updated"},
			{"Phoneme", "Phoneme"},
		},
	}
end

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

-- Split string by sep char
function 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

-- Get key pitch
function getKeyFromPitch(notePitch)
	local keyNames = {"C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"}
	local pitchPos = notePitch % 12
	return keyNames[pitchPos + 1]
end

-- Start check current group
function getGroup()
	local editor = SV:getMainEditor()
	local ref = editor:getCurrentGroup()

	if ref == nil then
		SV:showMessageBox(SV:T(SCRIPT_TITLE), SV:T("No group selected found!"))
	else		
		local noteGroup = ref:getTarget()
		
		-- Loop notes properties to get user updated phonemes if exists: noteGroup:getNumNotes()
		local notesProperties = getNotesProperties(noteGroup)
			
		-- Loop group note attributes to get all internal phonemes: getComputedAttributesForGroup
		-- and match user updated with notesProperties above
		local notesPhonemeAttributes = getGroupNotesAttributes(ref, notesProperties)
		
		-- Loop to display group note attributes result
		local result = displayResult(notesPhonemeAttributes)
		return result
	end
end

-- Loop to display 
function displayResult(notesPhonemeAttributes)
	local result = ""
	
	for k, v in pairs(notesPhonemeAttributes) do
		result = result .. SV:T("Note")  .. k
				.. " (".. getKeyFromPitch(v.note:getPitch())  .. ") "
				.. SV:T("lyrics") .. ": " .. v.note:getLyrics()
				.. "\r"

		if v.phonemesAttributesAndUpdated ~= nil then
			for l, n in pairs(v.phonemesAttributesAndUpdated) do
				-- Display phonemes attributes from group of notes
				result = result .. n.text
				
				-- Get updated phonemes on each phonemes notes
				if n.phonemesGroupContent ~= nil then
					local updatedInfos = ""
					
					-- Check if phonemes have been updated
					for o, p in pairs(n.phonemesGroupContent) do
						-- if p.symbol ~= nil then updatedInfos = updatedInfos .. "symbol=" .. p.symbol .. ", " end
						if p.positionUpd ~= nil then
							updatedInfos = updatedInfos .. SV:T("position") .. "=" .. p.positionUpd .. ", "
						end
						if p.activityUpd ~= nil then
							updatedInfos = updatedInfos .. SV:T("activity") .. "="  .. p.activityUpd .. ", "
						end
						if p.strength ~= nil then
							updatedInfos = updatedInfos .. SV:T("strength") .. "=" .. p.strength .. ", "
						end
					end
					-- Something updated?
					if #updatedInfos > 0 then
						-- result = result .. "\r"
						result = result .. SV:T("Updated") .. ":" .. updatedInfos
					end
					result = result .. "\r"
				else
					result = result .. "\r"
				end
			end
		else
			result = result .. "\r"
		end
	end
	return result
end

-- Loop group note attributes
function getGroupNotesAttributes(groupRef, notesProperties)
	local notesPhonemeAttributes = {}
	local attributes = SV:getComputedAttributesForGroup(groupRef)
	local phonemesAttributesAndUpdated = {}
	
	for iNote = 1, #attributes do
		local phonemes = attributes[iNote].phonemes
		local noteProperties = notesProperties[iNote]
		local iPhoneme = 0
		local phonemeText = ""
		phonemesAttributesAndUpdated = {} -- clearing for each note
		
		for k, v in pairs(phonemes) do
			iPhoneme = iPhoneme + 1
			phonemeText = "-" .. SV:T("Phoneme") .. iPhoneme .. ": "
			local phonemesGroupContent = {}
			if phonemes[k] ~= nil then
				-- phonemeText = phonemeText .. k .. "=" .. tostring(v) .. "\r"
				if type(v) == "table" then
					local symbol = nil
					local language = nil 
					local strength = nil
					local positionOri = nil 
					local activityOri = nil 
					local positionUpd = nil 
					local activityUpd = nil
					for l, n in pairs(v) do
						phonemeText = phonemeText .. l .. "=" .. tostring(n) .. ", "
						if l == "symbol" then
							symbol = n
						end
						if l == "language" then
							language = n
						end
						if l == "strength" then
							strength = n
						end
						if l == "position" then
							positionOri = n
						end
						if l == "activity" then
							activityOri = n
						end
					end
					
					local positionUpd = nil
					local activityUpd = nil
					local strengthUpd = nil
					
					-- Get updated notes phonemes
					if noteProperties.phonemes[k] ~= nil then
						for j, m in pairs(noteProperties.phonemes[k]) do
							if j == "position" then
								positionUpd = m
							end
							if j == "activity" then
								activityUpd = m
							end
							if j == "strength" then
								strength = m
							end
						end
					end
					
					-- Store all phonemes from group of notes 
					-- and user updated phonemes from loop of notes
					local phonemeGroupContent = {index = k, symbol = symbol, language = language, 
						strength = strength, positionOri = positionOri, activityOri = activity, 
						positionUpd = positionUpd, activityUpd = activityUpd, 
						strengthUpd = strengthUpd}
					table.insert(phonemesGroupContent, phonemeGroupContent)
				end
			end
			-- Store 
			table.insert(phonemesAttributesAndUpdated, {index=iPhoneme, 
				phonemesGroupContent=phonemesGroupContent, text=phonemeText})
		end
		
		local noteGroupContent = {index = iNote, note = noteProperties.note, 
			phonemes = noteProperties.phonemes, phonemesText = noteProperties.phonemesText, 
			attributes = noteProperties.attributes,
			phonemesGroup = phonemes, phonemesGroupText = phonemesText,
			phonemesAttributesAndUpdated = phonemesAttributesAndUpdated}
		table.insert(notesPhonemeAttributes, noteGroupContent)
	end
	return notesPhonemeAttributes
end

-- Loop notes properties to get user updated phonemes
function getNotesProperties(noteGroup)
	local notesProperties = {}
	for iNote = 1, noteGroup:getNumNotes() do
		local note = noteGroup:getNote(iNote)
		local phonemes = note:getAttributes().phonemes
		local phonemesText = ""
		
		if #phonemes > 0 then
			for k, v in pairs(phonemes) do
				phonemesText = phonemesText .. SV:T("Phoneme") .. " (" .. k .. "): "
				if type(v) == "table" then
					for l, n in pairs(v) do
						phonemesText = phonemesText .. l .. "=" .. tostring(n) .. ", "
					end
					phonemesText = phonemesText .. "\r"
				end
			end
		end
		local noteContent = {index = iNote, note = note, phonemes = phonemes, 
			phonemesText = phonemesText, attributes = note:getAttributes()}
		table.insert(notesProperties, noteContent)
	end
	return notesProperties
end

-- Main process
function main(notEndProcess)
	-- Get phonemes of the current group of notes
	local result = getGroup()
	
	-- Store to clipboard
	SV:setHostClipboard(result)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), result)
 
	if notEndProcess == nil then
		-- End of script
		SV:finish()
	end
end