-- Notecase Pro sample script (requires Notecase Pro >= 3.5.0)
--
-- Description:
-- Offers the selection dialog to load one group of documents (out of multiple possible defined groups) 
--
-- 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 < 5)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.5.0")
	return
end 

strStoreDir = Nc_Config_ConfigDir_Get()

-- 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

-- fill table with .session files found in a folder
tEntries = {}
for file in lfs.dir(strStoreDir) do
		if file ~= "." and file ~= ".." then
				local f = strStoreDir .. '/' .. file
				local attr = lfs.attributes (f)
				if attr.mode ~= "directory" then
					if string.find(file,"%.session$") then
						-- store file name without .session part
						tEntries[#tEntries + 1] =  string.sub(file, 0, -9) 
					end
				end
		end
end

-- show session selection dialog
nSelIdx = Nc_GUI_SelectionDlg("Load session", tEntries[1], tEntries[2], tEntries[3], tEntries[4], tEntries[5], tEntries[6], tEntries[7], tEntries[8], tEntries[9], tEntries[10], tEntries[11], tEntries[12])
if nSelIdx < 0 then
	return
end

strFileName = Nc_Config_ConfigDir_Get() .. tEntries[nSelIdx+1] .. ".session"
f = io.open(strFileName, "r")
if f == nil then
	Nc_GUI_MessageBox("Failed to open output file, aborting")
	return
end

-- read file content
local strData = f:read("*all")
f:close() 

-- close currently open documents
nCount = Nc_App_GetDocCount()
for i=nCount-1,0,-1 do
	nDocID = Nc_Doc_ID_GetByIdx(i)
	Nc_Doc_Close(nDocID)
end  

-- open the documents identified by the paths
local buf = lines(strData)
nSize = #buf
for i=1, nSize do
  Nc_Doc_Load(buf[i]) 
end 
