-- Notecase Pro sample script (requires Notecase Pro >= 3.1.4)
--
-- Description:
-- write to clipboard a list of all tags applied to the notes listed in List Pane, in alphanumeric ascending order.
--
-- This script's author, Miroslav Rajcic, hereby waives all copyright 
-- and related or neighboring rights to this script, pursuant to the
-- Creative Commons CC0 Universal relinquishment of rights found at
-- http://creativecommons.org/publicdomain/zero/1.0/

-- make sure app version supports necessary scriptable program commands
nMaj, nMin, nRev = Nc_Config_GetAppVersion()
if (nMaj < 3 or (nMaj == 3 and nMin < 1) or (nMaj == 3 and nMin == 1 and nRev < 4)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.1.4")
	return
end

-- break string into the array
function lines(str)
  local t = {}
  local i, lstr = 1, #str
  while i <= lstr do
    local x, y = string.find(str, "\r?\n", i)
    if x then t[#t + 1] = string.sub(str, i, x - 1)
    else break
    end
    i = y + 1
  end
  if i <= lstr then t[#t + 1] = string.sub(str, i) end
  return t
end

if 0 == Nc_App_List_GetState() then
	Nc_GUI_MessageBox("ERROR: Script works only on List Pane view")
	return
end

-- get info on the currently active document
nDocID = Nc_Doc_ID_GetCur()
nListPaneCount = Nc_App_List_GetCount()

strTags = ""

-- for each document note
for i=1,nListPaneCount do 
	-- get info on the note
	strNoteID    = Nc_App_List_Note_GetID(i-1)

	strTagsSingle = Nc_Note_Tags_Get(nDocID, strNoteID)
	strTags = strTags .. strTagsSingle
end  

-- delete first tag delimiter character
c = string.sub(strTags, 1, 1)
if c == ';' then
 strTags = string.sub(strTags, 2, string.len(strTags))
end

-- remove empty tags
strTags = string.gsub(strTags, ";;", ";")

-- replace delimiter with new line 
strTags = string.gsub(strTags, ";", "\n")

-- sort the text
local eol = string.match(strTags, "\n$")
local buf = lines(strTags)
table.sort(buf)

-- clear the duplicates
i = 1
while i <  #buf do
	if buf[i] == buf[i+1] then
			table.remove(buf, i+1)
	else
			i = i + 1
	end
end

local out = table.concat(buf, "\n")
if eol then out = out.."\n" end

strTags = out

-- Nc_GUI_MessageBox("Tags list:\n" .. strTags)

-- write text to clipboard

Nc_Env_Clipboard_Set(strTags, 0)
