/*------------------------------------------------------------------------
    File        : read.p
    Purpose     : Return all data from selected table as JSON, table name 
    				  is sent as 'table' parameter in request. If callback
    			 	  value set in request the data is wrapped inside the 
    			 	  callback function (JSONP)
  ----------------------------------------------------------------------*/
  
{src/web2/wrap-cgi.i}

/* ********************  Preprocessor Definitions  ******************** */


/* ***************************  Main Block  *************************** */
define variable jsonData   as longchar  no-undo.
define variable putOffset  as integer   no-undo.
define variable tblName    as character no-undo.
define variable cbName     as character no-undo.
define variable bufHdl     as handle    no-undo.
 
{io/akera/json/writer.i}

fix-codepage(jsonData) = 'utf-8'.

run GetValue('callback', output cbName).
run GetValue('table', output tblName).

if tblName = ? or tblName = '' then
	tblName = 'item'.

create buffer bufHdl for table tblName no-error.

if valid-handle(bufHdl) then   
	jsonData = json-write-all-array(bufHdl, '', '', '').
else 
	jsonData = '~{error: "Invalid database table: ' + tblName + '"~}'.

if cbName > '' then do:
	output-content-type('application/x-javascript; charset=utf-8':U).
	jsonData = cbName + '(':u + jsonData + ')':u.
end.
else 
	output-content-type('application/json; charset=utf-8':U).


do while putOffset < length(jsonData):
    {&OUT} string(substring(jsonData, putOffset + 1, 16000)).
    putOffset = putOffset + 16000.
end.
