-- Notecase Pro sample script (requires Notecase Pro >= 3.3.1)
--
-- Description:
-- export current document to the selected directory filled with RTF files (create a new file for each 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 < 5) or (nMaj == 3 and nMin == 5 and nRev < 1)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.5.1")
	return
end

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

-- get output folder
strTopLevel = Nc_GUI_FileDlg(1, "", "Pick Export Directory", "", 0, 1)

function ProcessDocument(strCurrentDir, strRootNoteID)

	local nChildCnt = Nc_Note_ChildCount(nDocID, strRootNoteID)
  for i=0, nChildCnt-1 do
			local strChildNoteID = Nc_Note_Child_GetID(nDocID, strRootNoteID, i)
			local strChildTitle  = Nc_Note_Title_Get(nDocID, strChildNoteID)
			local nSubChildCnt   = Nc_Note_ChildCount(nDocID, strChildNoteID)
			local strEntry = strCurrentDir..'/'..strChildTitle

      -- increment progress position
      nCurFile = nCurFile + 1
      Nc_GUI_ProgressDlg_SetPos(nCurFile) 
     
			if 0 == nSubChildCnt then
				-- export as file
				strEntry = strEntry .. ".rtf"
        Nc_Doc_Export(nDocID, strEntry, 1, strChildNoteID)	-- export single note
			else
				-- export as folder
				lfs.mkdir(strEntry)
				ProcessDocument (strEntry, strChildNoteID)

				-- if the note itself has content, export it as "index.rtf" file
				strEntry = strCurrentDir..'/'.. strChildTitle .. '/' .. "index.rtf"
				Nc_Doc_Export(nDocID, strEntry, 1, strChildNoteID)	-- export single note
      end
  end

end -- function

-- show import progress
nCurFile = 0
nTotalFiles = Nc_Doc_NoteCount(nDocID)
-- Nc_GUI_MessageBox("Total files:" .. nTotalFiles)
Nc_GUI_ProgressDlg_Start("Exporting notes", nTotalFiles)

ProcessDocument(strTopLevel, "")

Nc_Note_ID_SetCur("")
Nc_GUI_ProgressDlg_Close()
Nc_GUI_MessageBox("Done!")