local SCRIPT_TITLE = '.Project infos'

--[[

Synthesizer V Studio Pro Script
 
lua file name: ProjectInfosPanel.lua
Show information on the project
Track, voice, group count, note count.

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

Update: Add voice name for each group
		Minor update

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"] = {
			{"Project infos", "Project infos"},
			{"Version", "Version"},
			{"author", "author"},
			{"minEditorVersion", "minEditorVersion"},
			{"Clear project script data", "Clear project script data"},
			{"Project script data cleared!", "Project script data cleared!"},
			{"Remember to save this project!", "Remember to save this project!"},
			{"Infos copied: ", "Infos copied: "},
			{"chars", "chars"},
			{"Infos are empty!", "Infos are empty!"},
			{"File: ", "File: "},
			{"Version: ", "Version: "},
			{"Meter: ", "Meter: "},
			{"Tempo: ", "Tempo: "},
			{"Parameters:", "Parameters:"},
			{"VocalModes:", "VocalModes:"},
			{"Notes:", "Notes:"},
			{"Library: ", "Library: "},
			{"groups:", "groups:"},
			{"Track", "Track"},
			{"Tracks: ", "Tracks: "},
			{"Groups: ", "Groups: "},
			{"Index: ", "Index: "},
			{"Position: ", "Position: "},
			{"bpm", "bpm"},
			{"Voice: ", "Voice: "},
			{"transposeSemitones: ", "transposeSemitones: "},
			{"Group", "Group"},
			{"language", "language"},
			{"languageOverride", "languageOverride"},
			{"Voices list:", "Voices list:"},
			{"Notes: ", "Notes: "},
			{"Filename: ", "Filename: "},
			{"No filename", "No filename"},
			{"Duration: ", "Duration: "},
			{"s", "s"},
			{"Project script data:", "Project script data:"},
			{"Poject script data:", "Poject script data:"},
			{"Project svp file:", "Project svp file:"},
			{"groups", "groups"},
			{"notes", "notes"},
			{"group", "group"},
			{"note", "note"},
			{"Display project information:", "Display project information:"},
			{"Clipboard", "Clipboard"},
			{"Clear", "Clear"},
		},
	}
end

-- Define a class  "NotesObject"
NotesObject = {
	playBack = nil,
	playHeadPosition = nil,
	displayVersion = true,			-- display version
	displayAuthor = false,			-- display author
	errorMessages = {},
	hostinfo = nil,
	osType = "",
	osName = "",
	hostName = "",
	languageCode = "", 
	hostVersion = "",
	hostVersionNumber = 0,
	projectDurationBlicks = 0,
	projectDuration = 0,
	clearButtonValue = nil, 			-- button Clear lyrics
	clearScriptDataButtonValue = nil,	-- button clearScriptDataButtonValue
	applyButtonValue = nil, 			-- button apply get infos
	clipBoardButtonValue = nil,			-- button clipBoardButtonValue
	tracksList = {},
	projectInfos = "",
	labelApply = "",
	resultFiles = ""
}

-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
	self.labelApply = SV:T("Project infos")
	
	self:getHostInformations()

	self.controls = self:getControls()
	
	self:initializeControlsValues()
	self:setControlsCallback()
	
	self.clearButtonValue = SV:create("WidgetValue")
	self.clearScriptDataButtonValue = 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.projectInfosTextValue = SV:create("WidgetValue")
	self.projectInfosTextValue:setValue("")
	self.projectInfosTextValue:setEnabled(false)
	
	self:setButtonApplyControlCallback()
	self:setButtonclipBoardControlCallback()
	self:setButtonClearControlCallback()
	self:setButtonClearScriptDataControlCallback()
	
	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

-- Read file content
function NotesObject:readAll(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
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

-- 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

-- Get controls panel
function NotesObject:getControls()

	local controls = {
		control1 = {
			value = SV:create("WidgetValue"),
			defaultValue = 0, 
			paramKey = "control1"
		},
	}
	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 Apply control callback
function NotesObject:setButtonApplyControlCallback()

	-- Button copy lyrics to clipboard
	self.applyButtonValue:setValueChangeCallback(function()
			self.projectInfos = self:getProjectInfos()
			self.projectInfosTextValue:setValue(self.projectInfos)
			-- SV:refreshSidePanel()
		end
	)
end

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

	-- Button Clear text area control
	self.clearButtonValue:setValueChangeCallback(function()
			self.projectInfos = ""
			self.projectInfosTextValue:setValue(self.projectInfos)
			self:displayMessage("")
		end
	)
end

-- Set button Clear project script data control callback
function NotesObject:setButtonClearScriptDataControlCallback()

	-- Button clear project script data
	self.clearScriptDataButtonValue:setValueChangeCallback(function()
			SV:showOkCancelBoxAsync(SCRIPT_TITLE, SV:T("Clear project script data"), 
			function(response) self:clearProjectScriptData(response) end)
		end
	)
end

-- Clear project script data()
function NotesObject:clearProjectScriptData(response)
	if response then
		self:getProject():newUndoRecord()
		self.getProject():clearScriptData()
		self.projectInfos = ""
		self.projectInfosTextValue:setValue(self.projectInfos)
		self:displayMessage(SV:T("Project script data cleared!") .. "\r" .. SV:T("Remember to save this project!"))
	end
end

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

	-- Button 
	self.clipBoardButtonValue:setValueChangeCallback(function()
			-- self:getProject():newUndoRecord()
			if #self.projectInfos > 0 then
				SV:setHostClipboard(self.projectInfos)
				self:displayMessage(SV:T("Infos copied: ") .. #self.projectInfos .. " " .. SV:T("chars"))
			else
				self:displayMessage(SV:T("Infos are empty!"))
			end
		end
	)
end

-- Display message
function NotesObject:displayMessage(message)
	self:clearTextPanel()
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(message)
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

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

-- File processing
function NotesObject:fileProcess(file)
	-- Process one file
	local projectInfos = nil -- File, Libraries, TracksCount, TracksContent
	local infos = ""
	local jsonData = self:readAll(file)
	local groupsInTrack = {}
	local language = {}
	local languageOverride = {}
	
	if jsonData ~= nil then
		if #jsonData > 0 then
			local meterInfos = ""
			local tempoInfos = ""
			local libraryInfos = ""
			local tracksInfos = ""
			local groupsLibrary = {}
			infos = infos .. SV:T("File: ") .. file .. "\r"
			
			local js = json.parse(jsonData)
			-- {"version": 153, "time": {"meter": [{"index": 0, "numerator": 4, "denominator": 4}], "tempo": [{"position": 0, "bpm": 80.0}]}, "library":
			local version = js.version
			local time = js.time
			local meterArray = time.meter
			infos = infos .. SV:T("Version: ") .. version .. "\r"
			
			for iMeter = 1,  #meterArray do
				meterInfos = meterInfos .. meterArray[iMeter].index .. ", " .. meterArray[iMeter].numerator
					.. ", " .. meterArray[iMeter].denominator
			end
			infos = infos .. SV:T("Meter: ") .. meterInfos .. "\r"
			
			local tempoArray = time.tempo
			for iTempo = 1,  #tempoArray do
				tempoInfos = tempoInfos .. tempoArray[iTempo].position .. ", " .. tempoArray[iTempo].bpm
			end
			infos = infos .. SV:T("Tempo: ") .. tempoInfos .. "\r"
			
			local libraryArray = js.library
			if libraryArray ~= nil then
				for iLibrary = 1, #libraryArray do
					libraryInfos = libraryInfos .. libraryArray[iLibrary].name 
						.. ", " .. libraryArray[iLibrary].uuid .. "\r"
					
					table.insert(groupsLibrary, {indice = iLibrary, groupId = libraryArray[iLibrary].uuid, 
									groupName = libraryArray[iLibrary].name})
					
					local parameters = tostring(libraryArray[iLibrary].parameters)
					-- parameters.pitchDelta.mode
					-- parameters.pitchDelta.points
					local vocalModes = tostring(libraryArray[iLibrary].vocalModes)
					local notesArray = libraryArray[iLibrary].notes
					libraryInfos = libraryInfos .. SV:T("Parameters:") .. "\r" .. parameters .. "\r"
					libraryInfos = libraryInfos .. SV:T("VocalModes:") .. "\r" .. vocalModes .. "\r"
					
					local notesInfos = ""
					for iNote = 1,  #notesArray do
						notesInfos = notesInfos .. tostring(notesArray[iNote].musicalType)
							.. ", " .. notesArray[iNote].onset
							.. ", " .. notesArray[iNote].duration
							.. ", " .. notesArray[iNote].lyrics
							.. ", " .. notesArray[iNote].phonemes
							.. ", " .. tostring(notesArray[iNote].accent)
							.. ", " .. notesArray[iNote].pitch
							.. ", " .. notesArray[iNote].detune
							.. ", " .. tostring(notesArray[iNote].instantMode)
							.. "\r"
							-- .. ", " .. tostring(notesArray[iNote].systemAttributes)
							-- .. ", " .. tostring(notesArray[iNote].pitchTakes)
							-- .. ", " .. tostring(notesArray[iNote].timbreTakes)
					end
					libraryInfos = libraryInfos .. SV:T("Notes:") .. "\r" .. notesInfos
				end
				infos = infos .. SV:T("Library: ") .. libraryInfos .. "\r"
			end
			
			local tracksArray = js.tracks
			local tracksContent = {}
			
			if tracksArray ~= nil then
				for iTrack = 1,  #tracksArray do
					local groupsInfos = ""
					tracksInfos = tracksInfos .. tracksArray[iTrack].name
						.. ",  " .. tracksArray[iTrack].dispColor
						.. ",  " .. tracksArray[iTrack].dispOrder
						.. ",  " .. tostring(tracksArray[iTrack].renderEnabled)
						.. ",  " .. tracksArray[iTrack].mixer.gainDecibel
						.. ",  " .. tracksArray[iTrack].mixer.pan
						.. ",  " .. tostring(tracksArray[iTrack].mixer.mute)
						.. ",  " .. tostring(tracksArray[iTrack].mixer.solo)
						.. ",  " .. tostring(tracksArray[iTrack].mixer.display)
						.. ",  " .. tracksArray[iTrack].mainGroup.name
						.. ",  " .. tracksArray[iTrack].mainGroup.uuid
						.. ",  " .. tracksArray[iTrack].mainRef.groupID
						.. ",  " .. tostring(tracksArray[iTrack].mainRef.isInstrumental)
						.. ",  " .. tracksArray[iTrack].mainRef.database.name
						.. ",  " .. tracksArray[iTrack].mainRef.database.language
						.. ",  " .. tracksArray[iTrack].mainRef.database.phoneset
						.. ",  " .. tracksArray[iTrack].mainRef.database.languageOverride
						.. ",  " .. tracksArray[iTrack].mainRef.database.phonesetOverride
						.. ",  " .. tracksArray[iTrack].mainRef.database.backendType
						.. ",  " .. tracksArray[iTrack].mainRef.database.version
						.. ",  " .. tracksArray[iTrack].mainRef.dictionary
						.. ",  " .. tostring(tracksArray[iTrack].mainRef.voice.vocalModeInherited)
						.. ",  " .. tostring(tracksArray[iTrack].mainRef.voice.transposeSemitones)
						.. ",  " .. tracksArray[iTrack].mainRef.voice.vocalModePreset
						.. ",  " .. tostring(tracksArray[iTrack].mainRef.voice.vocalModeParams)
						.. "\r"
					
					local groupsArray =	tracksArray[iTrack].groups
					for iGroup = 1, #groupsArray do
						groupsInfos = groupsInfos .. groupsArray[iGroup].groupID
							.. ",  " .. tostring(groupsArray[iGroup].blickAbsoluteBegin)
							.. ",  " .. tostring(groupsArray[iGroup].blickAbsoluteEnd)
							.. ",  " .. tostring(groupsArray[iGroup].blickOffset)
							.. ",  " .. tostring(groupsArray[iGroup].pitchOffset)
							.. ",  " .. tostring(groupsArray[iGroup].isInstrumental)
							
						if groupsArray[iGroup].database ~= nil then
							groupsInfos = groupsInfos 
							.. ",  " .. groupsArray[iGroup].database.name
							.. ",  " .. groupsArray[iGroup].database.language
							.. ",  " .. groupsArray[iGroup].database.phoneset
							.. ",  " .. groupsArray[iGroup].database.languageOverride
							.. ",  " .. groupsArray[iGroup].database.phonesetOverride
							.. ",  " .. groupsArray[iGroup].database.backendType
							.. ",  " .. groupsArray[iGroup].database.version
						end
						groupsInfos = groupsInfos .. "\r"
						
						voiceName = tracksArray[iTrack].mainRef.database.name
						local newLanguage = groupsArray[iGroup].database.language  or ""
						local newLanguageOverride = groupsArray[iGroup].database.languageOverride  or ""
						local voiceName = tracksArray[iTrack].mainRef.database.name
						local groupId = groupsArray[iGroup].groupID
						local groupName = ""
						
						-- Get group info from Library node
						local isGroupFound, groupLibraryFound = self:getGroupFromGroupId(groupsLibrary, groupId)
						
						if isGroupFound then
							groupName = groupLibraryFound.groupName
						end
						groupsInTrack = self:setGroupsInTrack(groupsInTrack, iTrack, iGroup, voiceName, groupName, groupId, newLanguage, newLanguageOverride)
						
					end
					tracksInfos = tracksInfos .. SV:T("groups:") .. "\r".. groupsInfos
					
					table.insert(tracksContent, {SV:T("Track") .. " " .. iTrack, 
						{ track = tracksArray[iTrack].name, 
						  voice = tracksArray[iTrack].mainRef.database.name,
						  transposeSemitones = tracksArray[iTrack].mainRef.voice.transposeSemitones,
						  language = tracksArray[iTrack].mainRef.database.language,
						  languageOverride = tracksArray[iTrack].mainRef.database.languageOverride,
						  version = tracksArray[iTrack].mainRef.database.version,
						  groups = tracksArray[iTrack].groups}})
						  
				end
				
				infos = infos .. SV:T("Tracks: ") .. tracksInfos .. "\r"
				-- local  rCDestination = js.renderConfig.destination
				-- local  rCFilename = js.renderConfig.filename
				-- local  rCNumChannels = js.renderConfig.numChannels
				-- local  rCAspirationFormat = js.renderConfig.aspirationFormat
				-- local  rCBitDepth = js.renderConfig.bitDepth
				-- local  rCSampleRate = js.renderConfig.sampleRate
				-- local  rCExportMixDown = js.renderConfig.exportMixDown
				-- local  rCExportPitch = js.renderConfig.exportPitch
			end
			
			projectInfos = {
				filename = file, 
				version = version,
				meter = meterArray,
				tempo = tempoArray,
				librariesCount = #libraryArray,
				libraries = libraryArray,
				tracksCount = #tracksArray,
				tracksContent = tracksContent,
				groupsInTrack = groupsInTrack,
				infos = infos
			}
		end
	end
	return projectInfos
end

-- Set language of a group
function NotesObject:setGroupsInTrack(groupsInTrack, iTrack, iGroup, voiceName, groupName, groupId, language, languageOverride)
	local result = groupsInTrack
	local groupFound = false
	
	for i, group in ipairs(groupsInTrack) do
		if iTrack == group.track and iGroup == group.group then
			groupFound = true
			break
		end
	end
	if not groupFound then
		table.insert(groupsInTrack, {track = iTrack, group = iGroup, voiceName = voiceName, groupName = groupName, groupId = groupId,
		language = language, languageOverride = languageOverride})
	end
	return result
end

-- get group from groupId
function NotesObject:getGroupFromGroupId(groupLibrary, groupId)
	local groupFound = {}
	local found = false
	for _, group in ipairs(groupLibrary) do
		if group.groupId == groupId then
			groupFound = group
			found = true
			break
		end
	end
	return found, groupFound
end

-- Store result
function NotesObject:storeResult(projectInfos)
	local result = ""
	-- local isFilterInfoFound = false
	local transposeSemitonesResult = ""
	
	result = result .. projectInfos.filename
		.. "\r"
	result = result .. SV:T("Groups: ")  .. projectInfos.librariesCount
		.. ", " .. SV:T("Tracks: ") .. projectInfos.tracksCount
		.. "\r"
	
	local meterArray = projectInfos.meter
	local tempoArray = projectInfos.tempo
	local meterInfos = ""
	local tempoInfos = ""
	
	for iMeter = 1,  #meterArray do
		meterInfos = meterInfos .. SV:T("Index: ") .. meterArray[iMeter].index 
			.. ": (" .. meterArray[iMeter].numerator
			.. "/" .. meterArray[iMeter].denominator .. ")" .. " "
	end
	for iTempo = 1,  #tempoArray do
		tempoInfos = tempoInfos  .. SV:T("Position: ") .. tempoArray[iTempo].position 
		.. ": " .. tempoArray[iTempo].bpm .. " " .. SV:T("bpm") .. " "
	end			
		
	result = result .. SV:T("Meter: ") .. meterInfos .. "\r"
	result = result .. SV:T("Tempo: ") .. tempoInfos .. "\r"
		
	if #projectInfos.tracksContent > 0 then
		for iTrack = 1, #projectInfos.tracksContent do
			local transposeSemitones = projectInfos.tracksContent[iTrack][2].transposeSemitones
			-- Track
			result = result .. projectInfos.tracksContent[iTrack][1] .. ": "
			result = result .. projectInfos.tracksContent[iTrack][2].track  .. ", "
			result = result .. SV:T("Voice: ") .. projectInfos.tracksContent[iTrack][2].voice
			if transposeSemitones ~= nil then
				transposeSemitonesResult = transposeSemitonesResult .. transposeSemitones .. "|"
				result = result .. ", " .. SV:T("transposeSemitones: ") .. projectInfos.tracksContent[iTrack][2].transposeSemitones
			end
			local languageTrack = projectInfos.tracksContent[iTrack][2].language
			result = result .. " (" .. languageTrack

			local languageOverrideTrack = projectInfos.tracksContent[iTrack][2].languageOverride
			if #languageOverrideTrack > 0 and languageOverrideTrack ~= languageTrack then
				result = result .. ", " .. languageOverrideTrack
			end
			result = result .. ", " .. projectInfos.tracksContent[iTrack][2].version .. ")"
			.. "\r"
			
			if #projectInfos.groupsInTrack > 0 then
				for iGroup, group in ipairs(projectInfos.groupsInTrack) do
					if iTrack == group.track then
						local language = group.language
						local languageOverride = group.languageOverride
						
						result = result .."   " .. SV:T("Group") .. " " .. group.group .. " (" .. group.voiceName .. ")"
						if #language > 0 then
							result = result .. ": " .. SV:T("language") .. "        " .. ": " .. language
						end
						if #languageOverride > 0 then
							result = result .. ": " .. SV:T("languageOverride") .. ": " .. languageOverride
						end
						result = result .. " \"" .. group.groupName .. "\"" 
						result = result .. "\r"
					end
				end
			end
		end
		
		local voiceTitle = SV:T("Voices list:")
		result = result .. string.rep("-", #voiceTitle) .. "\r"
		result = result .. voiceTitle .. "\r"
		
		for iTrack = 1, #projectInfos.tracksContent do
			result = result .. projectInfos.tracksContent[iTrack][1] .. ": "
			result = result .. projectInfos.tracksContent[iTrack][2].track  .. ", "
			result = result .. SV:T("Voice: ") .. projectInfos.tracksContent[iTrack][2].voice 
			if #self.tracksList > 0 then
				result = result .. ", " .. SV:T("Notes: ") .. self.tracksList[iTrack].notes
			end
			result = result .. "\r"
		end
	end
	-- result = result .. projectInfos.infos  .. "\r"

	self.resultFiles = self.resultFiles .. result
	
	return result
end

-- Get project infos
function NotesObject:getProjectInfos()
	local infos = ""
	local resultSvpFile = ""
	local filename = ""
	local file = self:getProject():getFileName()
	local isFile = false
	
	if file ~= nil and #file > 0 then
		filename = SV:T("Filename: ") .. self:getFileNameOnly(file)
		isFile = true
	else
		filename = SV:T("No filename")
	end

	self.projectDurationBlicks = self:getProject():getDuration()
	self.projectDuration = self:getTimeAxis():getSecondsFromBlick(self.projectDurationBlicks)
	
	local durationLabel = SV:T("Duration: ") .. string.format("%0.2f", self.projectDuration) .. SV:T("s")
	local groupCount = SV:T("Groups: ") .. self:getProject():getNumNoteGroupsInLibrary()
	local trackCount = SV:T("Tracks: ") .. self:getProject():getNumTracks()
	local tracksInfos, tracksList = self:getTracksList()
	self.tracksList = tracksList
	local projectScriptData = ""
	local projectScriptDataKeys = self.getProject():getScriptDataKeys()
	
	if #projectScriptDataKeys > 0 then
		projectScriptData = SV:T("Project script data:") .. " (" .. #projectScriptDataKeys ..  ")" .. "\r"
		local displayStringLength = 15
		-- projectScriptData = SV:T("Poject script data:") .. "\r" .. table.concat(projectScriptDataKeys, "\r") .. "\r"
		for _, key in ipairs(projectScriptDataKeys) do
			if self.getProject():hasScriptData(key) then
				local data = self.getProject():getScriptData(key)
				local nextData = "..."
				if #data <= displayStringLength then
					nextData = ""
				end
				projectScriptData =  projectScriptData .. key .. "=" .. string.sub(data, 1, displayStringLength)  .. nextData .. "\r"
			end
		end
		projectScriptData = projectScriptData .. "\r"
	end

	infos = filename .. "\r"
		.. durationLabel .. "\r"
		.. groupCount .. ", " .. trackCount .. "\r"
		.. tracksInfos .. "\r"
		.. 	projectScriptData

		
	if isFile then
		local projectInfos = self:fileProcess(self:getProject():getFileName())
		
		if projectInfos ~= nil then
			resultSvpFile = SV:T("Project svp file:") .. "\r"
			resultSvpFile = resultSvpFile .. string.rep("-", #resultSvpFile) .. "\r"
			resultSvpFile = resultSvpFile .. self:storeResult(projectInfos)
		end
		
		infos = infos .. resultSvpFile
	end
		
	return infos
end

-- Get track list
function NotesObject:getTracksList()
	local list = ""
	local listTable = {}

	local formatCount = "%1d"
	local iTracks = self.getProject():getNumTracks()
	for iTrack = 1, iTracks do
		local track = self.getProject():getTrack(iTrack)
		local numGroups = track:getNumGroups() - 1
		local formatGroup = formatCount .. " " .. SV:T("groups")
		local formatNotes = formatCount .. " " .. SV:T("notes")

		local numNotes = 0
		for i = 1, track:getNumGroups() do
			local groupRef = track:getGroupReference(i)
			local groupNote = groupRef:getTarget()
			numNotes = numNotes + groupNote:getNumNotes()
		end
		
		if numGroups < 2 then
			formatGroup = formatCount .. " " .. SV:T("group")
		end
		if numNotes < 2 then
			formatNotes = formatCount .. " " .. SV:T("note")
		end
		
		table.insert(listTable, {track = iTrack, groups = numGroups, notes = numNotes})
		
		list = list .. track:getName() .. ": " 
			.. string.format(formatGroup, numGroups)
			.. ", " .. string.format(formatNotes, numNotes)
			.. "\r"
	end
	return list, listTable
end

-- Get section
function NotesObject:getSection()

	-- Define CheckBox & button & textarea
	local section = {
		title = SV:T(SCRIPT_TITLE),
		rows = {
			{
				type = "Label",
				text = SV:T("Display project information:"),
			},
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.projectInfosTextValue,
						height = 300,
						width = 1.0,
						readOnly = false
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "Button",
						text = self.labelApply,
						width = 1.0,
						value = self.applyButtonValue
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.statusTextValue,
						height = 60,
						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"),
						width = 0.5,
						value = self.clearButtonValue
					}
				}
			},
			{
				type = "Container",
				columns = {
					{
						type = "Button",
						text = SV:T("Clear project script data"),
						width = 1,
						value = self.clearScriptDataButtonValue
					}
				}
			}
		}
	}
	return section
end

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

	self.applyButtonValue: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()
	load_json()
	
	local section = notesObject:getPanelSectionState()

	return section
end

--https://gist.github.com/tylerneylon/59f4bcf316be525b30ab
--[[ json.lua

A compact pure-Lua JSON library.
The main functions are: json.stringify, json.parse.

## json.stringify:

This expects the following to be true of any tables being encoded:
 * They only have string or number keys. Number keys must be represented as
   strings in json; this is part of the json spec.
 * They are not recursive. Such a structure cannot be specified in json.

A Lua table is considered to be an array if and only if its set of keys is a
consecutive sequence of positive integers starting at 1. Arrays are encoded like
so: `[2, 3, false, "hi"]`. Any other type of Lua table is encoded as a json
object, encoded like so: `{"key1": 2, "key2": false}`.

Because the Lua nil value cannot be a key, and as a table value is considerd
equivalent to a missing key, there is no way to express the json "null" value in
a Lua table. The only way this will output "null" is if your entire input obj is
nil itself.

An empty Lua table, {}, could be considered either a json object or array -
it's an ambiguous edge case. We choose to treat this as an object as it is the
more general type.

To be clear, none of the above considerations is a limitation of this code.
Rather, it is what we get when we completely observe the json specification for
as arbitrary a Lua object as json is capable of expressing.

## json.parse:

This function parses json, with the exception that it does not pay attention to
\u-escaped unicode code points in strings.

It is difficult for Lua to return null as a value. In order to prevent the loss
of keys with a null value in a json string, this function uses the one-off
table value json.null (which is just an empty table) to indicate null values.
This way you can check if a value is null with the conditional
`val == json.null`.

If you have control over the data and are using Lua, I would recommend just
avoiding null values in your data to begin with.

--]]

function load_json()
	json = {}

	-- Internal functions.
	local function kind_of(obj)
	  if type(obj) ~= 'table' then return type(obj) end
	  local i = 1
	  for _ in pairs(obj) do
		if obj[i] ~= nil then i = i + 1 else return 'table' end
	  end
	  if i == 1 then return 'table' else return 'array' end
	end

	local function escape_str(s)
	  local in_char  = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'}
	  local out_char = {'\\', '"', '/',  'b',  'f',  'n',  'r',  't'}
	  for i, c in ipairs(in_char) do
		s = s:gsub(c, '\\' .. out_char[i])
	  end
	  return s
	end

	-- Returns pos, did_find; there are two cases:
	-- 1. Delimiter found: pos = pos after leading space + delim; did_find = true.
	-- 2. Delimiter not found: pos = pos after leading space;     did_find = false.
	-- This throws an error if err_if_missing is true and the delim is not found.
	local function skip_delim(str, pos, delim, err_if_missing)
	  pos = pos + #str:match('^%s*', pos)
	  if str:sub(pos, pos) ~= delim then
		if err_if_missing then
		  error('Expected ' .. delim .. ' near position ' .. pos)
		end
		return pos, false
	  end
	  return pos + 1, true
	end

	-- Expects the given pos to be the first character after the opening quote.
	-- Returns val, pos; the returned pos is after the closing quote character.
	local function parse_str_val(str, pos, val)
	  val = val or ''
	  local early_end_error = 'End of input found while parsing string.'
	  if pos > #str then error(early_end_error) end
	  local c = str:sub(pos, pos)
	  if c == '"'  then return val, pos + 1 end
	  if c ~= '\\' then return parse_str_val(str, pos + 1, val .. c) end
	  -- We must have a \ character.
	  local esc_map = {b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'}
	  local nextc = str:sub(pos + 1, pos + 1)
	  if not nextc then error(early_end_error) end
	  return parse_str_val(str, pos + 2, val .. (esc_map[nextc] or nextc))
	end

	-- Returns val, pos; the returned pos is after the number's final character.
	local function parse_num_val(str, pos)
	  local num_str = str:match('^-?%d+%.?%d*[eE]?[+-]?%d*', pos)
	  local val = tonumber(num_str)
	  if not val then error('Error parsing number at position ' .. pos .. '.') end
	  return val, pos + #num_str
	end


	-- Public values and functions.

	function json.stringify(obj, as_key)
	  local s = {}  -- We'll build the string as an array of strings to be concatenated.
	  local kind = kind_of(obj)  -- This is 'array' if it's an array or type(obj) otherwise.
	  if kind == 'array' then
		if as_key then error('Can\'t encode array as key.') end
		s[#s + 1] = '['
		for i, val in ipairs(obj) do
		  if i > 1 then s[#s + 1] = ', ' end
		  s[#s + 1] = json.stringify(val)
		end
		s[#s + 1] = ']'
	  elseif kind == 'table' then
		if as_key then error('Can\'t encode table as key.') end
		s[#s + 1] = '{'
		for k, v in pairs(obj) do
		  if #s > 1 then s[#s + 1] = ', ' end
		  s[#s + 1] = json.stringify(k, true)
		  s[#s + 1] = ':'
		  s[#s + 1] = json.stringify(v)
		end
		s[#s + 1] = '}'
	  elseif kind == 'string' then
		return '"' .. escape_str(obj) .. '"'
	  elseif kind == 'number' then
		if as_key then return '"' .. tostring(obj) .. '"' end
		return tostring(obj)
	  elseif kind == 'boolean' then
		return tostring(obj)
	  elseif kind == 'nil' then
		return 'null'
	  else
		error('Unjsonifiable type: ' .. kind .. '.')
	  end
	  return table.concat(s)
	end

	json.null = {}  -- This is a one-off table to represent the null value.

	function json.parse(str, pos, end_delim)
	  pos = pos or 1
	  if str == nil or pos > #str then error('Reached unexpected end of input, pos: ' .. pos) end
	  local pos = pos + #str:match('^%s*', pos)  -- Skip whitespace.
	  local first = str:sub(pos, pos)
	  if first == '{' then  -- Parse an object.
		local obj, key, delim_found = {}, true, true
		pos = pos + 1
		while true do
		  key, pos = json.parse(str, pos, '}')
		  if key == nil then return obj, pos end
		  if not delim_found then error('Comma missing between object items.') end
		  pos = skip_delim(str, pos, ':', true)  -- true -> error if missing.
		  obj[key], pos = json.parse(str, pos)
		  pos, delim_found = skip_delim(str, pos, ',')
		end
	  elseif first == '[' then  -- Parse an array.
		local arr, val, delim_found = {}, true, true
		pos = pos + 1
		while true do
		  val, pos = json.parse(str, pos, ']')
		  if val == nil then return arr, pos end
		  if not delim_found then error('Comma missing between array items.') end
		  arr[#arr + 1] = val
		  pos, delim_found = skip_delim(str, pos, ',')
		end
	  elseif first == '"' then  -- Parse a string.
		return parse_str_val(str, pos + 1)
	  elseif first == '-' or first:match('%d') then  -- Parse a number.
		return parse_num_val(str, pos)
	  elseif first == end_delim then  -- End of an object or array.
		return nil, pos + 1
	  else  -- Parse true, false, or null.
		local literals = {['true'] = true, ['false'] = false, ['null'] = json.null}
		for lit_str, lit_val in pairs(literals) do
		  local lit_end = pos + #lit_str - 1
		  if str:sub(pos, lit_end) == lit_str then return lit_val, lit_end + 1 end
		end
		local pos_info_str = 'position ' .. pos .. ': ' .. str:sub(pos, pos + 10)
		error('Invalid json syntax starting at ' .. pos_info_str)
	  end
	end

	return json
end
