require 'site'
package.path = package.path .. ';../nylabus/?.lua'

print 'Nylabus PLS Record Service'

local Nylon = require 'nylon.core'()
local wv = require 'nylon.debug'{ name = 'l-svc-plsrecord' }

local Sqlite  = require 'sqlite'
local db = Sqlite:new 'plstest.db'

local RPC = { identity = function(a) return a end }

local function getMetadataForId( oneId  )
   local recid = (db:selectOne('select title, dt_modified, dt_created from note where ROWID=?', oneId))
   recid.id = recid.ROWID
   recid.ROWID = nil
   return recid
end

local function getFullRecordForId( oneId  )
   local recid = (db:selectOne('select * from note where ROWID=?', oneId))
   recid.id = recid.ROWID
   recid.ROWID = nil
   return recid
end

local Table = require 'extable'

function RPC.getRecordMetadata( id )
   if type(id) == 'number' then -- single id
      return getMetadataForId( id )
   elseif type(id) == 'table' then -- todo: to optimize, use one SQL query
      if type(id[1]) == 'number' then -- found a list of ids
         return Table.map( getMetadataForId, id )
      end
   end
end

function RPC.getFullRecord( id )
   if type(id) == 'number' then -- single id
      return getFullRecordForId( id )
   elseif type(id) == 'table' then
      if type(id[1]) == 'number' then -- found a list of ids
         return Table.map( getFullRecordForId, id )
      end
   end
end

local Services = require 'nylaservice-svc'
Services.register( 'plsrecord', RPC )


Nylon.run()