local Nylon = require 'nylon.core'()

require 'NylonSqlite'

wv = require 'nylon.debug' { name = 'pls-sqlite' }

local Sqlite = {}

function Sqlite:new(dbname)
   local db = NylonSqlite(dbname)
   if not db then
      wv.log('error', 'db could not open name=%s', dbname)
      error 'no database'
   else
      wv.log('debug', 'db opened with success name=%s', dbname)
   end
   return setmetatable({ db = db }, { __index = Sqlite })
--   -- print(string.format("Sqlite:new db=%s", dbname))
--   return setmetatable({ 
--      db = NylonSqlite(dbname)
--    }, { __index = Sqlite })
end

function Sqlite:selectOne(sql,...)
   local rc
   if not self.db then
      wv.log('error', 'db invalid db=%s db.db = %s', tostring(self), type(self.db))
      -- error 'no database'
   end

--print( 'Pdcurses=', Pdcurses )
--print( 'NylonSqlite=', NylonSqlite )
--print( 'NylonSysCore=', NylonSysCore )
--print( 'NylonOs=', NylonOs )
--local db = NylonSqlite 'fts-test.db'
--print('db=', type(db))
--print('selectOne=', db.selectOne)
--
--   self.db:selectOne({}, 'select count(*) from notes', {})
   --
   wv.log('debug', 'select one sql=%s', sql);
   self.db:selectOne( function(r) rc = r end, sql, {...} )
   if not rc then
      -- 
   elseif rc.ROWID then
      rc.ROWID = tonumber(rc.ROWID)
   end
   return rc
end

function Sqlite:selectMany(sql,...)
   local results = {}
   self.db:selectMany( function(row)
                          table.insert(results,row) 
                       end, sql, {...} )
   return results
end

function Sqlite:exec(sql,...)
   return self.db:exec( sql, {...} )
end

function Sqlite:retryexec(sql,...)
   local dbrc
   local args = { ... }
   for i = 1, 7 do
      local rc, err = pcall(function()
                          dbrc = self.db:exec( sql, args )
      end)
      if rc then
         break
      end
      wv.log('error','could not exec [try %d, sql=%s], e=%s', i, sql, err)
      Nylon.self:sleep( 0.05 * (2 ^ i) )
   end
   return dbrc
end

function Sqlite:lastRowId()
   return self.db:lastRowId()
end

return Sqlite