--[[--

   Provides file archiving services for PLS system; send a list of file names, they will be copied to
   an archive directory and a URL path (from localhost) is returned.

   This is used by PLS system e.g., when copying a CF_HDROP file list from the clipboard.

--]]--

local config = {
   archiveDir = 'c:/m/notes/monthly',
   archiveUrl = '/notes/monthly',
}


local File = require 'filelib'
local Table = require 'extable'
local Numword = require 'numword'

math.randomseed(os.time())

require 'psbind'


local function runshell(shell, cord, cmd)
   local results = {}
--   local function runone(cord)
      wv.log('debug','Invoking powershell, cmd=%s',cmd)
      cord:cthreaded_multi(
         shell:cthread_invoke(cmd),
         function( rc ) table.insert(results,rc) end )
      wv.log('debug','Powershell invocation returned')
--   end
--   wv.log('debug','starting pshell request cord, cmd=%s', cmd)
--   local cord = Nylon.cord('pshell-request', runone)
--   Nylon.self:waiton(cord)
   return results
end

local function cordfn_bg_copy( cord )
   while true do
      collectgarbage()
      local msg = cord:getmsg()
      local shell = Psbind.Shell() -- shell is created here so that it will be closed while idle; these things suck memory
      for _, v in ipairs(msg) do
         local store = v.archpath
         local item = v.item
         wv.log('debug','copying "%s" to "%s"', item, store )
         runshell( shell, cord, string.format( 'mkdir %s', store ) )
         runshell( shell, cord, string.format( 'copy-item "%s" %s/', item, store ) )
      end
   end
end

local cord_bg_copy = Nylon.cord( 'bgcopy', cordfn_bg_copy )


local RPC = {}


function RPC.archiveFileList(fileList)
   local date = os.date( '%y.%m/%d', os.time() )
   local rand = Numword.to_s( math.random(6400) + 1376 )
   local docopies = {}
   local results = Table.map( function(item)
                            local base = File.leaf(item)
                            local subdir = date .. '/' .. rand
                            local store = File.joinpath( config.archiveDir, subdir )
                            table.insert( docopies, { item = item, archpath = store } )
                            local url = table.concat( { config.archiveUrl, subdir, base }, '/' )
                            return url
                          end, fileList )
   cord_bg_copy:msg( docopies )
   return results
end


return RPC