local SCRIPT_TITLE = '.Lyrics'

--[[

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

Notice: Works only with script panel 
		introduced with Synthesizer V version >= 2.1.2

Update: Minor updates
		Add check box limit lyrics to current track
		4 - Add sort groups by time 
		(online documentation issue:getGroupReference... The groups are sorted in ascending onset positions. => in fact not)

2025 - JF AVILES
--]]

function getClientInfo()
	return {
		name = SV:T(SCRIPT_TITLE),
		-- category = "_JFA_Panels",
		author = "JFAVILES",
		versionNumber = 4,
		minEditorVersion = 131329,
		type = "SidePanelSection"
	}
end

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

-- Generated by JFA TranslateScripts.lua
function getArrayLanguageStrings()
	return {
		["en-us"] = {
			{"Version", "Version"},
			{"author", "author"},
			{"minEditorVersion", "minEditorVersion"},
			{"Lyrics: ", "Lyrics: "},
			{"chars", "chars"},
			{"Lyrics copied: ", "Lyrics copied: "},
			{"Lyrics are empty!", "Lyrics are empty!"},
			{"Project: ", "Project: "},
			{"Display lyrics:", "Display lyrics:"},
			{"Limit to current track", "Limit to current track"},
			{"Display lyrics", "Display lyrics"},
			{"Display group name and time", "Display group name and time"},
			{"Clipboard", "Clipboard"},
			{"Clear lyrics", "Clear lyrics"},
		},
	}
end

-- Define a class "NotesObject"
NotesObject = {
	playBack = nil,
	playHeadPosition = nil,
	displayVersion = true,			-- display version
	displayAuthor = false,			-- display author
	isGroupNameDisplayed = false,	-- is group name and time displayed
	isLimitTrack = false,			-- is limit lyrics from current track
	errorMessages = {},
	hostinfo = nil,
	osType = "",
	osName = "",
	hostName = "",
	languageCode = "", 
	hostVersion = "",
	hostVersionNumber = 0,
	debug = false,
	controls = {},					-- controls panel
	clearButtonValue = nil, 		-- button Clear lyrics
	applyButtonValue = nil, 		-- button apply get lyrics
	clipBoardButtonValue = nil, 	-- button clipBoardButtonValue
	statusTextValue = nil,   		-- text panel
	lyricsTextValue = nil,			-- lyrics text panel
	lyricsTrack = "",
	lyricsException = {},
	infosToDisplay = "",
	logs = {}
}

-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
	self:getHostInformations()
	
	self.controls = self:getControls()	
	self:initializeControlsValues()
	self:setControlsCallback()
	
	self.clearButtonValue = SV:create("WidgetValue")
	self.applyButtonValue = SV:create("WidgetValue")
	self.clipBoardButtonValue = SV:create("WidgetValue")
	
	self.statusTextValue = SV:create("WidgetValue")
	self.statusTextValue:setValue("")
	self.statusTextValue:setEnabled(false)

	self.lyricsTextValue = SV:create("WidgetValue")
	self.lyricsTextValue:setValue("")
	self.lyricsTextValue:setEnabled(false)
	
	self:setButtonClearControlCallback()
	self:setButtonApplyControlCallback()
	self:setButtonclipBoardControlCallback()
	
	self.lyricsException = {"+", "++", "-", "br", "'", ".cl", ".pau", ".sil"}
	
	local infos = getClientInfo()

	self.infosToDisplay = ""
	if self.displayVersion then
		self.infosToDisplay = self.infosToDisplay .. SV:T("Version") .. ": " ..  infos.versionNumber
		if self.displayAuthor then
			self.infosToDisplay = self.infosToDisplay .. " - " .. SV:T("author") .. ": " .. infos.author
		end
	end
	-- self.infosToDisplay = self.infosToDisplay .. SV:T("minEditorVersion") .. ": " ..  infos.minEditorVersion
	self:addTextPanel(self.infosToDisplay)

    return self
end

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

-- Get selected groups
function NotesObject:getSelectedGroups()	
	return SV:getArrangement():getSelection():getSelectedGroups()
end

-- Get current track
function NotesObject:getCurrentTrack()
	return SV:getMainEditor():getCurrentTrack()
end

-- Get timeAxis
function NotesObject:getTimeAxis()
	return self:getProject():getTimeAxis()
end

-- Get project
function NotesObject:getProject()
	return SV:getProject()
end

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

-- Add log into self.logs
function NotesObject:addLogs(message)
	table.insert(self.logs, message)
end

-- Display logs into panel
function NotesObject:addLogsInPanel()
	for i = 1, #self.logs do
		self:addTextPanel(self.logs[i])
	end
end

-- Set lyrics text in panel
function NotesObject:setlyricsTrackTextPanel(lyricsTrack)
	self.lyricsTextValue:setValue(lyricsTrack)
end

-- Display message box in panel
function NotesObject:addTextPanel(message)
	local old = self.statusTextValue:getValue()
	local sepLine = "\r"
	if #old > 0 then
		message = old .. sepLine .. message
	end
	self.statusTextValue:setValue(message)
end

-- Clear display message in panel
function NotesObject:clearTextPanel()
	self.statusTextValue:setValue("")
end

-- Store error message
function NotesObject:error(message)
	table.insert(self.errorMessages, message)
end

-- set project modified
function NotesObject:setProjectUpdated()
	local currentTrack = self:getCurrentTrack()
	currentTrack:setName(currentTrack:getName())	
end

-- Clear user project data
function NotesObject:clearLyricsData()
	self.lyricsTrack = ""
end

-- Get controls panel
function NotesObject:getControls()

	local controls = {
		groupName = {
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "groupName"
		},
		limitTrack = {
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "limitTrack"
		}
	}
	return controls
end

-- Initialize widget values
function NotesObject:initializeControlsValues()
	-- Initialize widget values
	for key, control in pairs(self.controls) do
		control.value:setValue(control.defaultValue)
		-- self:addLogs(key .. "=" .. tostring(control.defaultValue))
		-- self:addLogs(key .. "=" .. self:getObjectProperties(control))
	end
end

-- Set controls callback
function NotesObject:setControlsCallback()
	for key, control in pairs(self.controls) do
		control.value:setValueChangeCallback(function()
				-- self:addLogsInPanel()
			end
		)
	end
end

-- Set button Clear control callback
function NotesObject:setButtonClearControlCallback()

	-- Button load notes
	self.clearButtonValue:setValueChangeCallback(function()
			self.lyricsTrack = ""
			self.lyricsTextValue:setValue(self.lyricsTrack)
			self:displayMessage("")
		end
	)
end

-- Set button Apply control callback
function NotesObject:setButtonApplyControlCallback()

	-- Button copy lyrics to clipboard
	self.applyButtonValue:setValueChangeCallback(function()
			-- local track = SV:getMainEditor():getCurrentTrack()
			self.lyricsTrack = self:getLyrics()
			self:setlyricsTrackTextPanel(self.lyricsTrack)
			
			self:displayMessage(SV:T("Lyrics: ") .. #self.lyricsTrack .. " " .. SV:T("chars"))
		end
	)
end

-- Set button clipBoard control callback
function NotesObject:setButtonclipBoardControlCallback()

	-- Button 
	self.clipBoardButtonValue:setValueChangeCallback(function()
			-- self:getProject():newUndoRecord()
			if #self.lyricsTrack > 0 then
				SV:setHostClipboard(self.lyricsTrack)
				self:displayMessage(SV:T("Lyrics copied: ") .. #self.lyricsTrack .. " " .. SV:T("chars"))
			else
				self:displayMessage(SV:T("Lyrics are empty!"))
			end
		end
	)
end
	
-- Display message
function NotesObject:displayMessage(message)
	self:clearTextPanel()
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(message)
end

-- Get lyrics from all tracks
function NotesObject:getLyrics()
	local project = SV:getProject()
	local timeAxis = project:getTimeAxis()
	local trackCount = project:getNumTracks()	
	local resultLyrics = {}
	local lyricsTable = {}
	local maxLyrics =  0
	local previousMaxLyrics =  0
	local trackReference = 1
	local trackReferenceOrder = 1
	local trackReferenceLyricsLength = 0
	local result = ""
	local lyricsToStore = ""
	local currentTrackIndex = SV:getMainEditor():getCurrentTrack():getDisplayOrder()
	
	self.isGroupNameDisplayed = self.controls.groupName.value:getValue()
	self.isLimitTrack = self.controls.limitTrack.value:getValue()
	
	lyricsToStore = lyricsToStore .. SV:T("Project: ") 
		.. self:getFileNameOnly(self:getProject():getFileName()) .. "\r"
	
	for iTrack = 1, trackCount do
		local track = project:getTrack(iTrack)
		local trackName = track:getName()
		local trackIndex = track:getDisplayOrder()
		maxLyrics = 0
		
		if not self.isLimitTrack or (self.isLimitTrack and trackIndex == currentTrackIndex) then
			resultLyrics = self:getTrackLyrics(track, timeAxis, 0)
			
			if #resultLyrics > 0 then
				
				for iGroups = 1, #resultLyrics do
					local lyricsInGroups = resultLyrics[iGroups]
					trackNumber = lyricsInGroups.track
					
					table.insert(lyricsTable, {
						trackOrder = resultLyrics.track,
						trackNumber = iTrack,
						trackName = trackName,
						groupName = lyricsInGroups.groupName,
						timeBegin  =  lyricsInGroups.timeBegin,
						timeEnd  =  lyricsInGroups.timeEnd,
						timeSecondBegin = lyricsInGroups.timeSecondBegin,
						timeSecondEnd = lyricsInGroups.timeSecondEnd,
						timeOffset = lyricsInGroups.timeOffset,
						groupIndex = lyricsInGroups.groupIndex,
						lyric = lyricsInGroups.lyricsGroup,
						lyricsSubGroups = lyricsInGroups.lyricsSubGroups
					})
					
					maxLyrics = maxLyrics + lyricsInGroups.lyricsLength
				 end
			end
			
			if maxLyrics > previousMaxLyrics then
				trackReference = iTrack
				trackReferenceOrder = track:getDisplayOrder()
				trackReferenceLyricsLength = maxLyrics
			end
			previousMaxLyrics = maxLyrics
		end

	end

	-- Result infos
	if #lyricsTable > 0 then
		local nextTrackLines = ""
		local nextGroupLines = ""
		local nextLyrics = ""
		local lineInc = 0
		local previousLyrics = ""
		-- local previousTimeBegin = 0
		local previousTrackNumber = 0
		
		for iGroups = 1, #lyricsTable do
				
			if previousTrackNumber == 0 or previousTrackNumber ~= lyricsTable[iGroups].trackNumber then
				lyricsToStore = lyricsToStore .. nextTrackLines
					.. "----------------------" .. "\r"
					.. "Track " .. "(" .. string.format("%02d", lyricsTable[iGroups].trackNumber) .. "): " 
					.. string.format("%-20s", lyricsTable[iGroups].trackName) .. " "
					.. "\r"
				nextGroupLines = ""
			end
			
			if self.isGroupNameDisplayed then
				lyricsToStore = lyricsToStore .. nextGroupLines
					.. "[Group " .. "(" .. string.format("%02d", lyricsTable[iGroups].groupIndex) .. "): "
					.. self:secondsToClock(lyricsTable[iGroups].timeSecondBegin) .. " - "
					.. self:limitStringLength(lyricsTable[iGroups].groupName, 30) .. "..." .. "]"
					.. "\r"
			else
				lyricsToStore = lyricsToStore .. nextGroupLines
			end
			
			nextLyrics = ""
			-- Subgroups
			local subGroupsCount = #lyricsTable[iGroups].lyricsSubGroups
			for iSubGroups = 1, subGroupsCount do
				lineInc = lineInc + 1
				local subGroup = lyricsTable[iGroups].lyricsSubGroups[iSubGroups]
				lyricsToStore = lyricsToStore  .. nextLyrics .. subGroup.lyricsGroup
				nextLyrics = " "
			end
			nextGroupLines = "\r\r"
			nextTrackLines = "\r\r"
			previousTrackNumber = lyricsTable[iGroups].trackNumber			
		end
	end

	return lyricsToStore
end

-- Get lyrics from tracks for all groups notes inside
function NotesObject:getTrackLyrics(track, timeAxis, secondDecayInput)
	local groupsCount = track:getNumGroups()
	local secondDecay = tonumber(secondDecayInput)
	local DAWOffset = timeAxis:getBlickFromSeconds(secondDecay)
	local firstNoteStarted = ""  
	local lineInc = 0
	local resultLyrics = {}
	local lyricsGroup = ""
	local groupsReference = {}
	
	for iGroup = 1, groupsCount do
		local ref = track:getGroupReference(iGroup)
		table.insert(groupsReference, ref)
	end
	table.sort(groupsReference, function(a, b) return a:getOnset() < b:getOnset() end)
	
	for iGroup = 1, groupsCount do
		-- local ref = track:getGroupReference(iGroup)
		local ref = groupsReference[iGroup]
		local noteGroup = ref:getTarget()
		local groupName = noteGroup:getName()
		local notesCount = noteGroup:getNumNotes()
		local lyricsSubGroups = {}
		local sepChar = ""
		
		if notesCount > 0 then
			local firstSecNotePos = nil
			local previousNote = nil
			local previousNotePos = nil
			local previousNoteDuration = nil
			local secPreviousNoteDuration = 0
			local TimeOffset = 0
			local lyricsLine = ""
			local lyricsLines = ""
			local previousLyrics = ""
			local previousNoteDurations = 0
			
			-- loop notes in group
			for iNote = 1, notesCount do
				local infos = ""
				local note = noteGroup:getNote(iNote)
				subGroupAdded = false
				
				if note ~= nil then
					local lyrics = note:getLyrics()
					
					TimeOffset = ref:getTimeOffset() - DAWOffset
					local notePos = note:getOnset()
					local secNotePos = timeAxis:getSecondsFromBlick(notePos + TimeOffset)
					
					if previousNotePos ~= nil then
						previousNoteDurations = previousNotePos + previousNoteDuration + TimeOffset
						secPreviousNoteDuration = timeAxis:getSecondsFromBlick(previousNoteDurations)
					end
					
					if string.len(lyrics) > 0 then
						if previousNote == nil then
							-- First note
							firstNotePos = note:getOnset()
							firstSecNotePos = timeAxis:getSecondsFromBlick(notePos + TimeOffset)
						end
						
						-- Filter char '+' & '-' & 'br' & .cl & .pau & .sil
						if self:isTextAccepted(lyrics) then
							sepChar = self:addSpaceChar(previousLyrics)
							
							-- Add lyrics for each note
							lyricsLine = self:simpleTrim(lyricsLine) .. sepChar .. self:simpleTrim(lyrics)
							previousLyrics = self:simpleTrim(lyrics)
						else
							previousLyrics = self:simpleTrim(lyrics)
							-- if iNote > 1 then
								if lyrics == "br" then
									lyricsLine = lyricsLine .. "\r"
									previousLyrics = ""
								end
							-- end
						end
						
					end
					previousNote = note
					previousNotePos = previousNote:getOnset()
					previousNoteDuration = previousNote:getDuration()
				end
			end
			
			if string.len(lyricsLine) > 0 then 
				lineInc = lineInc + 1
				sepChar = self:addSpaceChar(lyricsLine)
				lyricsLines = self:simpleTrim(lyricsLines) .. sepChar .. self:simpleTrim(lyricsLine)
					
				self:addLyricsSubGroups(lyricsSubGroups, track, groupName, iGroup, lineInc,
					previousNotePos, previousNoteDurations, 
					firstSecNotePos, secPreviousNoteDuration, TimeOffset, self:simpleTrim(lyricsLine))
			end
			
			-- Add lyrics and timing
			table.insert(resultLyrics, {
				track = track:getDisplayOrder(),
				trackName = track:getName(),
				groupName = groupName,
				groupIndex = iGroup - 1,
				timeBegin  =  previousNotePos,
				timeEnd  =  previousNoteDurations,
				timeOffset = TimeOffset,
				timeSecondBegin = firstSecNotePos,
				timeSecondEnd = secPreviousNoteDuration,
				lyricsGroup = lyricsLines,
				lyricsSubGroups = lyricsSubGroups,
				lyricsLength = string.len(lyricsLines)
			})

		end
	end
	
	return resultLyrics
  
end

-- Add lyrics for sub groups
function NotesObject:addLyricsSubGroups(lyricsSubGroups, track, groupName, groupIndex, subGroupIndex,
	previousNotePos, previousNoteDurations, firstSecNotePos, secPreviousNoteDuration, TimeOffset, lyricsLines)
	
	-- Add lyrics for sub groups and timing
	table.insert(lyricsSubGroups, {
		track = track:getDisplayOrder(),
		trackName = track:getName(),
		groupName = groupName,
		groupIndex = groupIndex,
		subGroupIndex = subGroupIndex,
		timeBegin  =  previousNotePos,
		timeEnd  =  previousNoteDurations,
		timeSecondBegin = firstSecNotePos,
		timeSecondEnd = secPreviousNoteDuration,
		timeOffset = TimeOffset,
		lyricsGroup = lyricsLines
	})
end

-- Add space between lyrics if they are stored in each note
function NotesObject:addSpaceChar(previousLyrics)
	local sepChar = ""
	local tempStr = ""
	local tempStrLen = string.len(previousLyrics)
	if string.len(previousLyrics)>0 then
		tempStr = string.sub(previousLyrics, -1)
		if tempStr ~= " " then
			sepChar = " "
		end
	end	
	return sepChar
end

-- Get string format from seconds
function NotesObject:secondsToClock(timestamp)
	return string.format("%02d:%02d:%06.3f", 
	  math.floor(timestamp/3600), 
	  math.floor(timestamp/60)%60, 
	  timestamp%60):gsub("%.",",")
end

-- Simple trim string
function NotesObject:simpleTrim(s)
  return string.gsub(s, '[ \t]+%f[\r\n%z]', '')
end

-- Display error messages
function NotesObject:displayErrors()
	local result = ""
	if #self.errorMessages > 0 then
		for _, m in pairs(self.errorMessages) do
			result = result .. m .. "\r"
		end
	end
	return result
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

-- Get object properties (debug only)
function NotesObject:getObjectProperties(obj, level)
	local result = ""
	local level = level or 0
	local maxLevel = 3
	level = level + 1
	
	for k, v in pairs(obj) do
		if obj[k] ~= nil then
			result = result .. "(level: " .. level .. ") " .. k .. "=" .. tostring(v) .. "\r"
			if type(v) == "table" then
				-- result = result .. ", size:" .. #v .. ": "
				if level < maxLevel then
					result = result .. self:getObjectProperties(v, level) .. "\r"
				else
					result = result .. "\r"
				end
			end
		end
	end
	return result
end

-- Limit string max length
function NotesObject:limitStringLength(resultLyrics, maxLengthResult)
	-- Limit string max length
	if string.len(resultLyrics) > maxLengthResult then
		local posStringChar = string.find(resultLyrics," ", maxLengthResult - 10)
		if posStringChar == nil then posStringChar = maxLengthResult end
		resultLyrics = string.sub(resultLyrics, 1, posStringChar)
	end
	return resultLyrics
end

-- Check lyrics "a" less than .1s for special effect
function NotesObject:isLyricsEffect(note)
	local result = false
	local notelength = self:getTimeAxis():getSecondsFromBlick(note:getDuration())
	-- ie: 0.0635
	if notelength < 0.1 then
		result = true
	end
	return result
end

-- Is lyrics is a text accepted
function NotesObject:isTextAccepted(lyrics)
	local result = true
	
	-- Filter char '+' & '++' & '-' & 'br' & .cl & .pau & .sil
	for i, lyricsExcept in pairs(self.lyricsException) do
		if lyrics == lyricsExcept then
			result = false
			break
		end
	end

	return result
end

-- Get section
function NotesObject:getSection()

	-- Define CheckBox & button & textarea
	local section = {
		title = SV:T(SCRIPT_TITLE),
		rows = {
			{
				type = "Label",
				text = SV:T("Display lyrics:"),
			},
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.lyricsTextValue,
						height = 300,
						width = 1.0,
						readOnly = false
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Limit to current track"),
					value = self.controls.limitTrack.value,
					width = 1.0
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "Button",
						text = SV:T("Display lyrics"),
						width = 1.0,
						value = self.applyButtonValue
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
					type = "CheckBox",
					text = SV:T("Display group name and time"),
					value = self.controls.groupName.value,
					width = 1.0
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.statusTextValue,
						height = 40,
						width = 1.0,
						readOnly = true
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "Button",
						text = SV:T("Clipboard"),
						width = 0.5,
						value = self.clipBoardButtonValue
					},
					{
						type = "Button",
						text = SV:T("Clear lyrics"),
						width = 0.5,
						value = self.clearButtonValue
					}
				}
			}
		}
	}
	return section
end

-- Get panel section state
function NotesObject:getPanelSectionState()

	self.clearButtonValue:setEnabled(true)
	self.applyButtonValue:setEnabled(true)
	self.clipBoardButtonValue:setEnabled(true)
	local errors = self:displayErrors()
	if #errors > 0 then
		self:addTextPanel(errors)
	end
	
	-- Get section data
	local section = self:getSection()

	return section
end

-- Initialize main internal object	
local notesObject = NotesObject:new()

-- Get panel section state called by Synthesizer V internal system
function getSidePanelSectionState()

	local section = notesObject:getPanelSectionState()

	return section
end
