--[[--
   Demonstrates application of diffs to obtain prior versions of record text
   Maybe useful for calling from external program, ie, ruby script
--]]--

require 'site'

local Nylon = require 'nylon.core'()
--local wv = require 'nylon.debug' { name = 'pls-main' }
local Sqlite  = require 'sqlite'
local Numword = require 'pls-numword'
local JSON    = require 'JSON' -- for debugging

local db = Sqlite:new 'plstest.db'

local nwid = arg[1]

local recid = string.match(nwid,'^%d') and tonumber(nwid) or Numword.to_i(nwid)

local record = db:selectOne('select rowid, title, detail from note where rowid=?', tonumber(recid) )

if record then
   if arg[2] then
      local Diff = require 'diff_match_patch'
      local rev = tonumber(arg[2])
      local patches = db:selectMany('select content from patch where id_note=? and revision >= ? order by revision desc', recid, rev)
      for _, patch in ipairs(patches) do
         local gdiff = Diff.patch_fromText( patch.content )
         record.detail = Diff.patch_apply( gdiff, record.detail )
      end
   end

   print( record.detail )
end