-- Notecase Pro sample script (requires Notecase Pro >= 3.1.3)
--
-- Description:
-- load the linked text file into the current 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

-- 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
 	
-- if valid file already registered for this note
filename = ""
nPropIdx = Nc_Note_CustProp_FindByName(nDocID, strCurNoteID, "ExportFile")
if nPropIdx >= 0 then
	filename = Nc_Note_CustProp_GetValueByIdx(nDocID, strCurNoteID, nPropIdx)
end	

-- if no file or invalid file name, pick file now
local f = nil
if filename ~= "" then
	f = io.open(filename, "r")
end
if f == nil then
	filename = Nc_GUI_FileDlg(0) 
	if filename == "" then
		return 
	end
	f = io.open(filename, "r")
end	

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

-- replace note content with the file content
Nc_Note_Content_Set(nDocID, strCurNoteID, t, 0)

-- store file name as a custom property
nPropIdx = Nc_Note_CustProp_FindByName(nDocID, strCurNoteID, "ExportFile")
if nPropIdx >= 0 then
	Nc_Note_CustProp_DeleteByIdx(nDocID, strCurNoteID, nPropIdx)
end
Nc_Note_CustProp_Append(nDocID, strCurNoteID, "ExportFile", filename)