-- Notecase Pro sample script (requires Notecase Pro >= 3.2.1)
--
-- Description:
-- Automatically assign tag to the note if you find any tag that exists in the document within the note text
-- 
-- 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 < 2) or (nMaj == 3 and nMin == 2 and nRev < 1)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.2.1")
	return
end

-- prepare search patter for case-insensitive find
function nocase (s)
   s = string.gsub(s, "%a", function (c)
            return string.format("[%s%s]", string.lower(c),
                                           string.upper(c))
			end)
	return s
end

-- case-insensitive find 
function find_insensitive(str, pattern)
	return string.find(str, nocase(pattern), 1)
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 

-- get info on the currently active document/note
nDocID = Nc_Doc_ID_GetCur()
strCurNoteID = Nc_Note_ID_GetCur(nDocID)

if strCurNoteID == "" then
 	Nc_GUI_MessageBox("No note selected, aborting")
	return 
end

strText = Nc_Note_Content_Get(nDocID, strCurNoteID, 0)
strAllTags = Nc_Doc_Tags_Get(nDocID)

-- Nc_GUI_MessageBox("All tags: " .. strAllTags)
-- Nc_GUI_MessageBox("Note text: " .. strText)

-- convert tags to list
strAllTags = string.gsub(strAllTags, ";", "\n")
local tableLines = lines(strAllTags)  

-- preserve the old tags
strOldTags = Nc_Note_Tags_Get(nDocID, strCurNoteID)

-- create a new keyword string
strTagString = ";"
nTableSize = # tableLines
-- Nc_GUI_MessageBox("All tags count: " .. nTableSize)

for i=1,nTableSize do
	-- Nc_GUI_MessageBox("Test Tag [" .. tableLines[i] .. "]")
	
	-- find current tag in the note text
	local x, y = find_insensitive(strText, tableLines[i])
	-- find current tag in already existign tags
	local z, w = find_insensitive(strOldTags, ";" .. tableLines[i] .. ";")

	if x and not z then
		-- tag is in text and not already in the note tags, add it
		-- Nc_GUI_MessageBox("Tag [" .. tableLines[i] .. "] added")
		strTagString = strTagString .. tableLines[i]
		strTagString = strTagString .. ";"
	end
end

if string.len(strTagString) > 1 then
	-- Nc_GUI_MessageBox(strTagString)
	strTagString = strOldTags .. strTagString
	-- finally set the tags
	Nc_Note_Tags_Set(nDocID, strCurNoteID, strTagString)
end