-- Notecase Pro sample script (requires Notecase Pro >= 3.4.2)
--
-- Description:
-- demonstrates usage of socket a socket APIs to fetch a web page using a HTTP protocol (GET command)
--
-- 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 < 4) or (nMaj == 3 and nMin == 4 and nRev < 2)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.4.2")
	return
end 

-- settings
strHost = "www.bug.hr"
strURI = "/"
nPort = 80

-- connect
nSocket = net.connect(strHost, nPort)

-- send HTTP request
net.write(nSocket, "GET " .. strURI .. " HTTP/1.1\r\nHost: " .. strHost .. "\r\n\r\n")

-- read HTTP response
strReply = ""
repeat
	nSize, strChunk = net.read(nSocket)
	strReply = strReply .. strChunk
until nSize <= 0
  
-- disconnect
net.close(nSocket)

-- strip the HTTP header part
local x, y = string.find(strReply, "\r\n\r\n", 1)
if x then 
	strReply = string.sub(strReply, x + 4) 
end

-- now process the contents
Nc_GUI_InfoBox(strReply)

-- insert received HTML as a new note
-- nDocID = Nc_Doc_ID_GetCur()
-- strNoteID = Nc_Note_Insert(nDocID, "", -1, strHost)
-- Nc_Note_Content_Set(nDocID, strNoteID, strReply, 1) 