require 'site'
local Nylon = require 'nylon.core'()
local wv = require 'nylon.debug' { name = 'pls-main' }

local filename = '/tmp/scratch'

if arg[1] then
   filename = arg[1]
end

require 'LbindPdcurses'

local Buffer = require 'pls-buffer'


local bbuffer = Buffer.openFile( filename )


local gl_keybindings = {
   [3] = 'quit',  -- ctrl+c
   [27] = 'quit', -- esc
}

local keyhandler

-- global, meh
function request_keys( cbfun )
   local old = keyhandler
   local enabled = true
   keyhandler = function(k)
      local handled = (enabled and cbfun(k)) or (old and old(k))
      wv.log('norm','keyhandled? %d=%s', k, handled and 'yes' or 'no')
   end
   return function()
      enabled = false
   end
end


local function entryfn_input( cord, controller )
   wv.log '001 entryfn_input'

   Pdcurses.Static.keypad(true);

   wv.log '002 entryfn_input'

   cord:cthreaded_multi( Pdcurses.Static.cthread_getch_loop(), 
      function( k )
         wv.log('norm','entryfn_input got key=%d',k)
         -- controller:msg{ key = k }
         if gl_keybindings[k] == 'quit' then
            Pdcurses.Static.endwin()
            os.exit(1)
         else
            wv.log('norm','keyhandler[%d]=%s',k,keyhandler)
            if keyhandler then
               keyhandler(k)
            end
         end
      end )
end



local function curses_init()
   local screen = Pdcurses.Static.initscr()
   Pdcurses.Static.noecho()
   Pdcurses.Static.start_color()
   local ncols, nrows = screen:getmaxx(), screen:getmaxy()
   Pdcurses.Static.refresh()
   return { screen = screen, ncols = ncols, nrows = nrows }
end


local function WindowDim( x, y, w, h )
   return { x = x, y = y, w = w, h = h }
end



local function make_editor( env )
   local ed = require 'pls-ed'

   local nrows, ncols = env.curses.nrows, env.curses.ncols
   local x, y, w, h = math.floor(ncols/4), math.floor(nrows/4), math.floor(ncols/2), math.floor(nrows/2)
   local win = Pdcurses.Window( h, w, y, x )
   local wb = Pdcurses.Window(h+2,w+2,y-1,x-1)
   wb:stdbox_()
   wb:refresh()
   --local win = env.curses.screen

   local statuswin = Pdcurses.Window(1,w+2,y+h+1,x-1)
   local function winstatus( sttype, data )
      statuswin:mvaddstr(0,0,'[__')
      statuswin:addstr(data)
      statuswin:addstr('__]')
      local left = w - 6 - #data + 2
      statuswin:addstr(string.rep('_',left))
      statuswin:refresh()
   end

   local e = setmetatable( { w = win,
                             report = winstatus
                           }, { __index = env } )


   local cord_edit  = Nylon.cord( 'edit', ed.entryfn_edit, WindowDim(0,0,w,h), bbuffer, e )
end


local e = { curses = curses_init() }

local cord_input = Nylon.cord( 'input', entryfn_input, cord_keycontroller )

make_editor( e )

Nylon.run()