-- Notecase Pro sample script (requires Notecase Pro >= 3.1.3)
--
-- Description:
-- fills the flat list view with all the notes that share at least one common tag with the currently selected document note
--
-- 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 < 3)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.1.3")
	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

-- get info on the currently active document
nDocID = Nc_Doc_ID_GetCur()
strCurNoteID = Nc_Note_ID_GetCur(nDocID)
if strCurNoteID:len() == 0 then
 	Nc_GUI_MessageBox("No note selected, aborting")
	return 
end

Nc_App_List_Clear()
Nc_App_List_Switch(1) 

strTags = Nc_Note_Tags_Get(nDocID, strCurNoteID)

-- delete first tag delimiter character
c = string.sub(strTags, 1, 1)
if c == ';' then
 strTags = string.sub(strTags, 2, string.len(strTags))
end
-- replace delimiter with new line 
strTags = string.gsub(strTags, ";", "\n") 
-- create the tag list
local eol = string.match(strTags, "\n$")
local listTagsCur = lines(strTags) 

-- for each document note
nNoteCount = Nc_Doc_NoteCount(nDocID)
for i=1,nNoteCount do 
	-- get info on the note (note indexes start from 0)
	strNoteID    = Nc_Note_ID_GetByIdx(nDocID, i-1)

	-- for each note except the current one
	if strNoteID ~= strCurNoteID then 
		strTags = Nc_Note_Tags_Get(nDocID, strNoteID)
		
		-- delete first tag delimiter character
		c = string.sub(strTags, 1, 1)
		if c == ';' then
		 strTags = string.sub(strTags, 2, string.len(strTags))
		end
		-- replace delimiter with new line 
		strTags = string.gsub(strTags, ";", "\n") 
		-- create the tag list
		local eol = string.match(strTags, "\n$")
		local listTags = lines(strTags) 
		
		-- see if this note has any matching tag with current note
		nMatch = 0
		nSize1 = #listTagsCur
		nSize2 = #listTags
		for j=1, nSize1 do
		 for k=1, nSize2 do
			if listTagsCur[j] == listTags[k] then
				nMatch = 1
				break
			end
			if nMatch == 1 then
				break
			end
		 end
		end

		-- if match then add note to the list pane
		if nMatch == 1 then
			Nc_App_List_AddNote(strNoteID)
		end

	end

end  

