--[[
 * ReaScript Name: Convert region subtitles for the dedicated web browser interface
 * About: Have a track named lyrics and text items on it. Run the web interface.
 * Screenshot: https://cloud.extremraym.com/sharex/reascripts/Desktop+2019-04-19+12.32.50.mp4
 * Author: X-Raym
 * Author URI: https://www.extremraym.com
 * Repository: GitHub > X-Raym > REAPER-ReaScripts
 * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts
 * Licence: GPL v3
 * Link: Forum https://forum.cockos.com/showthread.php?p=2127630#post2127630
 * REAPER: 5.0
 * Version: 1.1
--]]

--[[
 * Changelog:
 * v1.1 (2021-02-11)
  + Send dummy text if notes == "", for having instructions on web interface is script is not running.
 * v1.0 (2019-08-26)
  + Initial Release
 --]]

 -- Set ToolBar Button State
function SetButtonState( set )
  if not set then set = 0 end
  local is_new_value, filename, sec, cmd, mode, resolution, val = reaper.get_action_context()
  local state = reaper.GetToggleCommandStateEx( sec, cmd )
  reaper.SetToggleCommandState( sec, cmd, set ) -- Set ON
  reaper.RefreshToolbar2( sec, cmd )
end

function Exit()
  reaper.SetProjExtState( 0, "XR_Lyrics", "text", "" )
  SetButtonState()
end


-- Main Function (which loop in background)
function main()

  -- Get play or edit cursor
  if reaper.GetPlayState() > 0 then
    cur_pos = reaper.GetPlayPosition()
  else
    cur_pos = reaper.GetCursorPosition()
  end

  marker_idx, region_idx = reaper.GetLastMarkerAndCurRegion(0, cur_pos)
  if region_idx >= 0 then -- IF LAST REGION

    retval, is_region, region_start, region_end, region_name, markrgnindexnumber, region_color = reaper.EnumProjectMarkers3(0, region_idx)
    region_notes = reaper.NF_GetSWSMarkerRegionSub( region_idx )
    if region_notes ~= notes then
      notes = region_notes
      if notes == "" then notes = "--XR-NO-TEXT--" end
      reaper.SetProjExtState( 0, "XR_Lyrics", "text", notes )
    end

  else

    if notes then
      notes = nil
    end

    reaper.SetProjExtState( 0, "XR_Lyrics", "text", "--XR-NO-TEXT--" )

  end

  reaper.defer( main )

end


notes = nil

-- RUN
SetButtonState( 1 )
main()
reaper.atexit( Exit )
