local Sqlite  = require 'sqlite'

local context_t = {
   url = 1,
   plsupdate = 2,
   plsnew = 3,
}

local db = Sqlite:new 'db-contexts.db'


local function addNewClipText( clip )
   if string.find( clip, '^http://') or string.find( clip, '^https://') then
      print('got URL clip=', clip)
      wv.log('debug', 'got URL clip=%s', clip)
      db:exec('insert into context (context_t, dt_created, data) values(?, DATETIME("NOW"), ?)',
              context_t.url, clip)
   end
end

local function cord_clipboard_monitor( cord )
   require 'NylonOs'
   local lastClip
   while true do
      -- wv.log('debug', 'clipboard monitor running')
      local clip = NylonOs.Static.getclipboard()
      if clip ~= lastClip then
         lastClip = clip
         addNewClipText( clip )
      end
      cord:sleep(0.3)
   end
end

local cb_cord = Nylon.cord('clipboard-mon', cord_clipboard_monitor )


local Table = require 'extable'

function cleanupctxrecord( record )
   if record.extern_id then
      record.extern_id = tonumber(record.extern_id)
   end
   if record.context_t then
      record.context_t = tonumber(record.context_t)
   end
   return record
end


local RPC = {}

function RPC.getContext()
   wv.log('debug', 'got call to getContext')
   local many = db:selectMany( 'select * from context where dt_created > (datetime("NOW")-14) order by dt_created desc' )
   --local many = db:selectMany( 'select * from context order by dt_created desc where dt_created limit 100' )
   return Table.map( cleanupctxrecord, many )
end


function RPC.getRecentContext( N )
   N = N or 20
   wv.log('debug', 'got call to getRecentContext, N=%d', N)
   local many = db:selectMany( 'select * from context where dt_created > (datetime("NOW")-14) order by dt_created desc limit ?', N )
   --local many = db:selectMany( 'select * from context order by dt_created desc where dt_created limit 100' )
   return Table.map( cleanupctxrecord, many )
end

function RPC.updatePlsRecord( recordId )
   wv.log('debug', 'PLS edit, record id=%d', recordId)
   print('PLS edit, record id=', recordId)
   db:exec('insert into context (context_t, dt_created, extern_id) values(?, DATETIME("NOW"), ?)',
           context_t.plsupdate, recordId)
end

function RPC.newPlsRecord( recordId )
   wv.log('debug', 'NEW PLS record, record id=%d', recordId)
   print('NEW PLS record, record id=', recordId)
   db:exec('insert into context (context_t, dt_created, extern_id) values(?, DATETIME("NOW"), ?)',
           context_t.plsnew, recordId)
end

return RPC