--[[

NoteCase Pro script
    See http://www.notecasepro.com/

SCRIPT NAME: 64_ModifyImageFormats.lua

   v. 1.0

PURPOSE: This script converts all embedded images in current document to a desired image format (either JPEG or PNG).

USAGE INSTRUCTIONS:  Make the document whose notes you wish to process the current document, then execute this script.

RIGHTS: 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
local nMaj, nMin, nRev = Nc_Config_GetAppVersion()
if (nMaj < 4 or (nMaj == 4 and nMin < 6) or (nMaj == 4 and nMin == 6 and nRev < 4)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 4.6.4")
	return
end

function process_note(nDocID, strNoteID)
  -- select note
  nImgCnt = Nc_Note_Image_GetCount(nDocID, strNoteID)
  for i=nImgCnt,1,-1 do
    nPos = Nc_Note_Image_Position_Get(nDocID, strNoteID, i-1)
    nFmt = Nc_Note_Image_Format_Get(nDocID, strNoteID, i-1)
    strData = Nc_Note_Image_Data_Get(nDocID, strNoteID, i-1)
    Nc_Note_Image_Remove(nDocID, strNoteID, i-1)
    -- Nc_GUI_MessageBox("Image " .. i .. " for note: '" .. Nc_Note_Title_Get(nDocID, strNoteID).. "' -> offset:" .. nPos .. " , old fmt:" .. nFmt .. " , data_len= " .. #strData)
    Nc_Note_Image_Insert_Mem(nDocID, strNoteID, nPos, strData, nFmtIdx)
  end  
end


-- ask desired format, JPEG or PNG
t = {}
t[1] = "JPEG"
t[2] = "PNG"
nFmtIdx = Nc_GUI_SelectionDlgTbl("Image format", t, "Please select format to apply to all images in current document.\nRead-only document notes will be skipped.\n\nWARNING: changing format type can introduce image quality degradation!", 0, 600, 400)
if nFmtIdx < 0 then
	return
end

-- get doc info
local nDocID = Nc_Doc_ID_GetCur()
local nReadOnly = Nc_Doc_ReadOnly_Get(nDocID)

-- abort script if doc is read-only
if nReadOnly == 1 then
	Nc_GUI_InfoBox("ERROR: Document is read-only;  no changes possible.", 1, "ERROR")
	return
end -- if nReadOnly

-- for each note
local nTotalNotes = Nc_Doc_NoteCount(nDocID)
for i=1,nTotalNotes do

   -- do the action if the note is not read-only
   local strNoteID = Nc_Note_ID_GetByIdx(nDocID, i-1)
   if Nc_Note_Flag_ReadOnly_Get(nDocID, strNoteID) ~= 1 then
      process_note(nDocID, strNoteID)
   end -- if

end -- for each

Nc_GUI_MessageBox("Done!")