--[[--
   Demonstrates application of diffs to restore record text from zero.
   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 Diff = require 'diff_match_patch'
--local rev = tonumber(arg[2])

local inittext = ''

local s = Nylon.uptime()
local patches = db:selectMany('select rcontent from patch where id_note=? order by revision asc', recid)
for ndx, patch in ipairs(patches) do
   local gdiff = Diff.patch_fromText( patch.rcontent )
   inittext = Diff.patch_apply( gdiff, inittext )
end
local e = Nylon.uptime()

print(inittext)
print(string.format('Time: %f\n',(e-s)))