local SCRIPT_TITLE = 'Group create from DAW V1.2'

--[[

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

Version for Synthesizer V version >= 2.1.1

Drag and drop notes from DAW: Automate group creation
1/ Waiting any newly created track
2/ Move imported DAW notes into a new group of notes
Version with dialog box

Note: Stopping this script:
A/ If you want to STOP this script without the required drag&drop DAW (multiple options): 
	A- STOP this script by creating a new note on the piano roll
	B- STOP this script by selecting a new existing note
	C- STOP this script by running this script again! 
		(hidden group used for this feature)

Update: 0 - Minor updates
		6 - Add multiple group creation after dropping chords notes from DAW
		7 - Update to script data instead of hidden group

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"] = {
			{"Track", "Track"},
			{"Waiting: ", "Waiting: "},
			{"Error nil value with param: ", "Error nil value with param: "},
			{"Error in saved parameters, try again!", "Error in saved parameters, try again!"},
			{"Song position: ", "Song position: "},
			{"OK to start waiting DAW drag & drop!", "OK to start waiting DAW drag & drop!"},
			{"Create a new track", "Create a new track"},
			{"Update 'SIL' or overlay notes", "Update 'SIL' or overlay notes"},
			{"Click OK to start waiting a drag & drop from DAW.", "Click OK to start waiting a drag & drop from DAW."},
			{"To abort this script waiting drag&drop: Run it again!", "To abort this script waiting drag&drop: Run it again!"},
		},
	}
end

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

-- Define a class  "NotesObject"
NotesObject = {
	project = nil,
	timeAxis = nil,
	editor = nil,
	THRESHOLD = 41505882,  -- 0.03 seconds (120)
	INITIAL_TRACK_NAME_REF = "initialTrackName",
	NUM_TRACKS_REF = "numTracks",
	CURRENT_TRACK_REF = "currentTrack",
	IS_NEW_TRACK = "isNewTrack",
	LINK_NOTES_ACTIVE = "linkNotesActive",
	TRACK_TARGET_REF = "trackTarget",
	scriptDataKey = "SCRIPT_Project_DROP_TO_POS",
	scriptStopDataKey = "SCRIPT_Project_STOP_DROP",
	scriptDataKeys = {},
	scriptDataKeysList = {},
	linkNotesActive = true,
	trackTarget = nil,
	trackTargetName = SV:T("Track"),
	initialTrackName = "",
	scriptInstance = "",
	newDAWTrack = nil,
	newGrouptRef = nil,
	currentTrack = nil,
	newAudioTrack = nil,
	isNewTrackSelected = false,
	numTracks = 0,
	selection = nil,
	selectedNotes = nil,
	numSelectedNotes = 0,
	dialogTitle = "",
	playBack = nil,
	currentSeconds = 0,
	stopProcess = false,
	stopProcessOK = false,
	processing = 0,
	isTrackClone = true, -- clone current track voice
	sepParam = "|",
	lyricsException = {}
}

-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
    self.project = SV:getProject()
    self.timeAxis = self.project:getTimeAxis()
    self.editor =  SV:getMainEditor()
	self.numTracks = self.project:getNumTracks()
	
	self.selection = self.editor:getSelection()
	self.selectedNotes = self.selection:getSelectedNotes()
	self.numSelectedNotes = #self.selection:getSelectedNotes()
	
	self.playBack = SV:getPlayback()
	self.currentSeconds = self.playBack:getPlayhead()
	self.currentTrack = self.editor:getCurrentTrack()
	self.initialTrackName = self.currentTrack:getName()
	self.trackTarget = self.currentTrack
	self.lyricsException = {"+", "++", "-", "br", "'", ".cl", ".pau", ".sil"}
	
    return self
end

-- Get track notes count
function NotesObject:getTrackNumNotes(track)
	local numNotes = 0
	for iGroupNote = 1, track:getNumGroups() do
		local groupRef = track:getGroupReference(iGroupNote)
		local group = groupRef:getTarget()
		numNotes = numNotes + group:getNumNotes()
	end
	return numNotes
end

--- Get last created track
function NotesObject:getLastTrack()
	return self.project:getTrack(self.project:getNumTracks())
end

-- Display message box
function NotesObject:show(message)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), message)
end

-- Get time max gap between notes
function NotesObject:getMaxTimeGapFromBPM(positionSeconds)
	local THRESHOLDBlicks = self.THRESHOLD
	local coef = 17 -- Convert 1/quarterBlicks to 0.03 seconds (120)
	local bpm = self:getProjectTempo(positionSeconds)
	
	if bpm ~= nil then
		-- "120:" time: 0.03s, 1s: blicks 1411200000 quarter 2
		-- "60: " time: 0.06s, 1s: blicks 705600000 quarter 1
		local blicks = SV:seconds2Blick(1, bpm) -- get blicks 1 second with bpm
		local quarterBlicks = SV:blick2Quarter(blicks)
		local gapMax = (1/quarterBlicks) / coef  -- result gap in seconds
		THRESHOLDBlicks = self.timeAxis:getBlickFromSeconds(gapMax)
	end
	return THRESHOLDBlicks
end

-- Get current project tempo
function NotesObject:getProjectTempo(seconds)
	local tempoActive = 120
	local blicks = self.timeAxis:getBlickFromSeconds(seconds)
	local tempoMarks = self.timeAxis:getAllTempoMarks()
	for iTempo = 1, #tempoMarks do
		local tempoMark = tempoMarks[iTempo]
		if tempoMark ~= nil and blicks >= tempoMark.position then
			tempoActive = tempoMark.bpm
		end
	end
	return math.floor(tempoActive)
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

-- Get first mesure before first note
function NotesObject:getFirstMesure(notePos)
	local measurePos = 0
	local measureBlick = 0
	local measureFirst = self.timeAxis:getMeasureAt(notePos)
	local checkExistingMeasureMark = self.timeAxis:getMeasureMarkAt(measureFirst)
	
	if checkExistingMeasureMark ~= nil then
		if checkExistingMeasureMark.position == measureFirst then
			measurePos = checkExistingMeasureMark.position
			measureBlick = checkExistingMeasureMark.positionBlick
		else 
			self.timeAxis:addMeasureMark(measureFirst, 
						checkExistingMeasureMark.numerator, 
						checkExistingMeasureMark.denominator)
			local measureMark = self.timeAxis:getMeasureMarkAt(measureFirst)
			measurePos = measureMark.position
			measureBlick = measureMark.positionBlick
			self.timeAxis:removeMeasureMark(measureFirst)
		end
	else
		-- Temporary measure mark addition
		self.timeAxis:addMeasureMark(measureFirst, 4, 4)
		local measureMark = self.timeAxis:getMeasureMarkAt(measureFirst)
		measurePos = measureMark.position
		measureBlick = measureMark.positionBlick
		self.timeAxis:removeMeasureMark(measureFirst)
	end
	return measureBlick
end

-- Remove track DAW
function NotesObject:removeTrackDAW()
	if self.newDAWTrack ~= nil then
		self.project:removeTrack(self.newDAWTrack:getIndexInParent())
		self.newDAWTrack = nil
	end
end

-- Remove track info if new track
function NotesObject:removeTrackTargetForNewTrack()
	if self.isNewTrackSelected then
		if self.trackTarget ~= nil then
			-- self:show(self.trackTarget:getIndexInParent() .. "\r" .. self.currentTrack:getIndexInParent())
			if self.trackTarget:getIndexInParent() ~= self.currentTrack:getIndexInParent() then
				self.project:removeTrack(self.trackTarget:getIndexInParent())
			end
			self.trackTarget = nil
		end
	end
end

-- Clone track to keep current track voice
function NotesObject:cloneTrackReference(trackRef, trackName)
	local newTrack = trackRef:clone()
	local iGroups = newTrack:getNumGroups()
	
	if iGroups > 1 then
		-- Delete groups
		while iGroups > 1 do
			local groupRef = newTrack:getGroupReference(iGroups)
			local index = groupRef:getIndexInParent()
			if groupRef ~= nil and not groupRef:isMain() then
				newTrack:removeGroupReference(index)
				iGroups = newTrack:getNumGroups()
			end
		end
	end
	
	newTrack:setName(trackName)
	self.project:addTrack(newTrack)

	return newTrack
end

-- Create track target
function NotesObject:createTrackTarget(name)
	local newTrackTarget = SV:create("Track")
	
	local newTrackIndex = self.project:addTrack(newTrackTarget)
	newTrackTarget = self.project:getTrack(newTrackIndex)
	newTrackTarget:setName(name)	
	return newTrackTarget
end

-- Create group for new track with new notes
function NotesObject:createGroup(startPosition, targetPosition)
	local maxLengthResult = 30
	local groupRefMain = self.newDAWTrack:getGroupReference(self.newDAWTrack:getNumGroups())
	local durationGroupRefMain = groupRefMain:getDuration()
	local groupNotesMain = groupRefMain:getTarget()
	local isChordsGroup = false
	
	local mainGroupNotes = {}
	
	local iGroup = 1
	self.THRESHOLD = self:getMaxTimeGapFromBPM(targetPosition) -- 41505882 = 0.06 seconds
	local previousNote = nil

	-- Save notes to groups
	for iNote = 1, groupNotesMain:getNumNotes() do
		local note = groupNotesMain:getNote(iNote)
		if previousNote ~= nil then
			if note:getOnset() == previousNote:getOnset() then
				isChordsGroup = true
				iGroup = iGroup + 1
			else
				iGroup = 1
			end
		end
		if mainGroupNotes[iGroup] == nil then
			mainGroupNotes[iGroup] = {}
		end
		table.insert(mainGroupNotes[iGroup], note)
		previousNote = groupNotesMain:getNote(iNote)
	end

	if #mainGroupNotes > 0 then
		for iGroup, group in ipairs(mainGroupNotes) do
			-- Create new group 
			local noteGroup = SV:create("NoteGroup")
			local newGrouptRef = SV:create("NoteGroupReference")
				
			self.project:addNoteGroup(noteGroup)
			newGrouptRef:setTarget(noteGroup)
			newGrouptRef:setTimeOffset(startPosition)
			newGrouptRef:setTimeRange(startPosition, durationGroupRefMain) -- v2.1.1
			
			if not self.isNewTrackSelected then
				self.currentTrack:addGroupReference(newGrouptRef)
			else
				local trackName = self.initialTrackName .. "-" .. self.project:getNumTracks()
				
				if self.isTrackClone then
					-- Clone track for new groups
					self.trackTarget = self:cloneTrackReference(self.currentTrack, trackName)
					self.trackTarget:addGroupReference(newGrouptRef)
					self.numTracks = self.project:getNumTracks()
					self:storeToProjectScriptData()
				else
					self.trackTarget = self:createTrackTarget(trackName)
					self.trackTarget:addGroupReference(newGrouptRef)
					self.numTracks = self.project:getNumTracks()
					self:storeToProjectScriptData()
				end
			end

			local previousNote = nil
			for iNote = 1, #group do
				local note = group[iNote]:clone()
				-- Update position within the new group
				note:setOnset(group[iNote]:getOnset())
				
				if self.linkNotesActive then
					if previousNote ~= nil then
						self:linkedTheNotes(previousNote, note, noteGroup:getNote(iNote - 1))
					end
				end
				
				noteGroup:addNote(note)
				previousNote = note
			end
			
			local resultLyrics = self:renameOneGroup(self.timeAxis, maxLengthResult, noteGroup)
		end
	end
	
	return true
end

-- Linked the notes
function NotesObject:linkedTheNotes(previousNote, note, storedNote)
	local gapNotes = previousNote:getEnd() - note:getOnset()
	-- SIL = 29400000 => 0.02s
	-- if iNote == 2 then 
		-- self:show("gapNotes: " .. gapNotes .. ", " 
		-- .. self.timeAxis:getSecondsFromBlick(gapNotes))
	-- end
	
	-- Notes overlay
	if gapNotes > 0 then
	-- if previousNote:getEnd() > note:getOnset() then
		-- Reduce previous note duration
		storedNote:setDuration(previousNote:getDuration() - gapNotes)
	end
				
	-- SIL = short time between notes
	if gapNotes < 0 and math.abs(gapNotes) < self.THRESHOLD then
		-- Spread previous note duration
		storedNote:setDuration(previousNote:getDuration() + math.abs(gapNotes))
	end
end

-- Rename one group
function NotesObject:renameOneGroup(timeAxis, maxLengthResult, noteGroup)
	local resultLyrics = ""
	local groupName = noteGroup:getName()
	local notesCount = noteGroup:getNumNotes()

	if notesCount > 0 then
		local lyricsLine = ""
		local sep = ""

		for i = 1, notesCount do
			local infos = ""
			local note = noteGroup:getNote(i)
			
			if note ~= nil then
				local lyrics = note:getLyrics()
				if string.len(lyrics) > 0 then
				
					-- Filter char '+' & '-' & 'br' & .cl & .pau & .sil
					if self:isTextAccepted(timeAxis, note) then
						-- Replace following note char '-'
						if lyrics == "-" then lyrics = ".." end 
						-- Add lyrics for each note
						lyricsLine = lyricsLine .. sep .. lyrics
						sep = " "
					end				  
				end
			end
		end

		-- Add lyrics
		resultLyrics = self:limitStringLength(lyricsLine, maxLengthResult)
		-- Update if new lyrics only
		if string.len(resultLyrics)> 0 and
			noteGroup:getName() ~= resultLyrics then
			noteGroup:setName(resultLyrics)
		end
	end

	return resultLyrics
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(timeAxis, note)
	local result = false
	local notelength = timeAxis:getSecondsFromBlick(note:getDuration())
	-- ie: 0.0635
	if notelength < 0.1 then
		result = true
	end
	return result
end

-- Is lyrics is a text accepted new
function NotesObject:isTextAcceptedNew(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

-- Is lyrics is a text accepted
function NotesObject:isTextAccepted(timeAxis, note)
	local result = false
	local lyrics = note:getLyrics()
	
	if self:isTextAcceptedNew(lyrics) then
		result = true
	end
	
	-- Specific for personal vocal effect
	if lyrics == "a" and self:isLyricsEffect(timeAxis, note) then
		result = false
	end

	return result
end

-- Set track name waiting
function NotesObject:setTrackNameWaiting()
	if self.trackTarget ~= nil then
		self.processing = self.processing  + 1
		if self.processing > 4 then
			self.processing = 0
		end
		local followString = string.rep(".", self.processing)
		self.currentTrack:setName(followString .. " " .. self.initialTrackName)
	end
end

-- Main loop
function NotesObject:loop()
	local newSelectedNotes = #self.selection:getSelectedNotes()
	local cause = ""

	if self:isScriptProjectDataStopped() then
		self.stopProcess = true
	end
	
	if self.numSelectedNotes ~= newSelectedNotes then
		cause = "Selected notes: " .. self.numSelectedNotes .. "/" .. newSelectedNotes
		self.stopProcess = true
	end
	
	if self.stopProcess then
		-- self:show("cause: " .. cause)
		self:endOfScript()
	else
		-- if a new same script instance is running or track is deleted by another script
		if self.numTracks > self.project:getNumTracks() then
			self.stopProcess = true
			self:endOfScript()
		else
			-- Scan a new track
			self:scanNewTrack()
			
			if not self.stopProcess then
				SV:setTimeout(500, function() self:loop() end)
			else
				self:endOfScript()
			end
		end
	end	
end

-- Scan a new track
function NotesObject:scanNewTrack()
	SV:setTimeout(10, function() self:setTrackNameWaiting() end)
	
	self.currentSeconds = self.playBack:getPlayhead()
	local secondsInfo = self:secondsToClock(self.currentSeconds)
	
	-- Check if a new track is created
	if self.numTracks < self.project:getNumTracks() then
		self.newDAWTrack = self:getLastTrack()
		local numNotesNewDAWTrack = self:getTrackNumNotes(self.newDAWTrack)		
		
		if numNotesNewDAWTrack > 0 then			
			local newStartPosition = self.timeAxis:getBlickFromSeconds(self.currentSeconds)
			local measureBlick = self:getFirstMesure(newStartPosition)

			-- New notes => Create a new group
			self:createGroup(measureBlick, self.currentSeconds)
			self:removeTrackDAW()
			self.stopProcess = true -- End of process
			self.stopProcessOK = true -- End of process OK
			self:setInitialTrackName()
		else
			-- a new track is created with no notes (audio?)
			self.newAudioTrack = self:getLastTrack()
			local numGroups = self.newAudioTrack:getNumGroups()
			
			if numGroups == 1 then
				local groupRef = self.newAudioTrack:getGroupReference(1)
				local groupTarget = groupRef:getTarget()
				if groupRef ~= nil then
					-- Audio?
					if groupRef:isInstrumental() then
						local groupOnset = groupRef:getOnset()
						local newStartPosition = self.timeAxis:getBlickFromSeconds(self.currentSeconds)
						local duration = groupRef:getDuration()
						if duration > 0 then
							groupRef:setTimeRange(newStartPosition, duration)
							groupRef:setTimeOffset(newStartPosition)					
							self.stopProcess = true		-- End of process
							self.stopProcessOK = true	-- End of process OK
							self:setInitialTrackName()
						end
					end
				end
			end
		end
	end
end

-- Stop script 
function NotesObject:stopScript()
	self.stopProcess = true
	SV:finish()
end

-- Set track target
function NotesObject:setTrackTarget()
	local targetName = self.initialTrackName
	-- if self.isNewTrackSelected and self.currentTrack ~= self.trackTarget then
	if self.isNewTrackSelected then
		targetName = self.initialTrackName .. "-" .. self.project:getNumTracks()
	end
	if self.trackTarget ~= nil then
		SV:setTimeout(10, function() self.trackTarget:setName(targetName) end)
	end
end

-- Set initial track name
function NotesObject:setInitialTrackName()
 
	if self.currentTrack ~= nil then
		self.currentTrack:setName(self.initialTrackName)
	end
end

-- Clear user project data
function NotesObject:clearProjectData()
	self.projectDataInfos = ""
	self.project:removeScriptData(self.scriptDataKey)
	self.project:removeScriptData(self.scriptStopDataKey)
end

-- Save user project data
function NotesObject:saveProjectData(data)
	self.project:setScriptData(self.scriptDataKey, data)
end

-- Get user project data
function NotesObject:getProjectData()
	local projectData = ""
	projectData = self.project:getScriptData(self.scriptDataKey) or ""
	return projectData
end

-- Get user stop project data
function NotesObject:getStopProjectData()
	local stopProjectData = ""
	stopProjectData = self.project:getScriptData(self.scriptStopDataKey) or ""
	return stopProjectData
end

-- Get user project data stopped
function NotesObject:isScriptProjectDataStopped()
	local result = false
	local stopProjectData = self:getStopProjectData()
	if #stopProjectData > 0 then 
		result = true
	end
	return result
end

-- End of script 
function NotesObject:endOfScript()
	self.stopProcess = true

	if not self.stopProcessOK then
		-- if error remove created target track
		SV:setTimeout(20, function() self:removeTrackTargetForNewTrack() end)	
	end
	
	SV:setTimeout(20, function() self:setInitialTrackName() end)

	-- clean previous data
	SV:setTimeout(20, function() self:clearProjectData() end)
	SV:setTimeout(100, function() self:finishScriptProcess() end)
end

-- Finish script processing
function NotesObject:finishScriptProcess()	
	-- End of script
	SV:finish()
end

-- trim string
function NotesObject:trim(s)
	  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

-- Get stored project data 
function NotesObject:getStoredProjectData()
	local result = false
	local data = self:getProjectData()

	if data ~= nil and #data > 0 then

		local paramSlitted = self:split(data, self.sepParam)
		for iLine = 1, #paramSlitted do
			local param = paramSlitted[iLine]
			local paramArray = self:split(param, "=")
			local paramKey = ""
			local paramValue = ""
			
			if paramArray[1] ~= nil then
				paramKey = self:trim(paramArray[1])
			end
			
			if paramArray[2] ~= nil then
				paramValue = self:trim(paramArray[2])
			end
			self:setParametersFromStoredData(paramKey, paramValue)
		end		
		result = true
	end

	return result
end

-- Set parameters from stored data
function NotesObject:setParametersFromStoredData(paramName, value)
	if string.find(paramName, self.INITIAL_TRACK_NAME_REF) then
		self.initialTrackName = value
	end
	if string.find(paramName, self.NUM_TRACKS_REF) then
		self.numTracks = tonumber(value)
	end	
	if string.find(paramName, self.TRACK_TARGET_REF) then
		local iTrack = tonumber(value)
		if iTrack <= self.numTracks then
			self.trackTarget = self.project:getTrack(iTrack)
		end
	end
	if string.find(paramName,self.CURRENT_TRACK_REF) then
		local iTrack = tonumber(value)
		if iTrack <= self.numTracks then
			self.currentTrack = self.project:getTrack(iTrack)
		end
	end
	if string.find(paramName, self.IS_NEW_TRACK) then
		self.isNewTrackSelected = false
		if value == "true" then 
			self.isNewTrackSelected = true
		end
	end
	if string.find(paramName, self.LINK_NOTES_ACTIVE) then
		self.linkNotesActive = false
		if value == "true" then 
			self.linkNotesActive = 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

-- Store data to project script data
function NotesObject:storeToProjectScriptData()
	
	local data = self.INITIAL_TRACK_NAME_REF	.. "=" .. self.initialTrackName					.. self.sepParam
		.. self.IS_NEW_TRACK					.. "=" .. tostring(self.isNewTrackSelected)		.. self.sepParam
		.. self.LINK_NOTES_ACTIVE				.. "=" .. tostring(self.linkNotesActive)		.. self.sepParam
		.. self.NUM_TRACKS_REF					.. "=" .. self.numTracks						.. self.sepParam
		.. self.TRACK_TARGET_REF				.. "=" .. self.trackTarget:getIndexInParent()	.. self.sepParam
		.. self.CURRENT_TRACK_REF				.. "=" .. self.currentTrack:getIndexInParent()	.. self.sepParam

	-- Get this stored data
	self:saveProjectData(data)
	
	-- Get this stored project data
	self:getStoredProjectData()
end

-- Stop process
function NotesObject:stopCurrentProcess()
	self.stopProcess = true
	self.project:setScriptData(self.scriptStopDataKey, "STOP")
end

-- Dialog response callback
function NotesObject:dialogResponse(response)
	
	if response.status then		
		self.project:newUndoRecord()
		self.isNewTrackSelected = response.answers.isNewTrack
		self.linkNotesActive = response.answers.linkNotesActive
		self.currentTrack = SV:getMainEditor():getCurrentTrack()
		self.initialTrackName = self.currentTrack:getName()
		self.trackTarget = self.currentTrack
		self.numTracks = self.project:getNumTracks()
		
		self:storeToProjectScriptData()
		
		SV:setTimeout(100, function() self:loop() end)
	else
		self:endOfScript()
	end
end

-- Show asynchrone custom dialog box
function NotesObject:showDialogAsync(title)
	
	self.currentSeconds = self.playBack:getPlayhead()
	local seconds = self:secondsToClock(self.currentSeconds)
	
	local form = {
		title = SV:T(SCRIPT_TITLE),
		message = title,
		buttons = "OkCancel",
		widgets = {
			{
				name = "timePosition", type = "TextArea", label = SV:T("Song position: ") .. seconds,
				height = 0, default = ""
			},
			{
				name = "info", type = "TextArea", label = SV:T("OK to start waiting DAW drag & drop!"), 
				height = 0, default = ""
			},
			{
				name = "isNewTrack",
				text = SV:T("Create a new track"),
				type = "CheckBox",
				default = false
			},
			{
				name = "linkNotesActive",
				text = SV:T("Update 'SIL' or overlay notes"),
				type = "CheckBox",
				default = true
			},
			{
				name = "separator", type = "TextArea", label = "", height = 0
			}
		}
	}
	self.dialogTitle = title
	self.onResponse = function(response) self:dialogResponse(response) end
	SV:showCustomDialogAsync(form, self.onResponse)	
end

-- Start process
function NotesObject:startProcess()
	
	-- Is first script processing
	if not self:getStoredProjectData() then
		
		local title = SV:T("Click OK to start waiting a drag & drop from DAW.")
					 .. "\r" .. SV:T("To abort this script waiting drag&drop: Run it again!")

		self:showDialogAsync(title)		
	else
		self:stopCurrentProcess()
		SV:setTimeout(100, function() self:endOfScript() end)
	end
end

-- Main processing task	
function main()
	local notesObject = NotesObject:new()
	notesObject:startProcess()
end
