local esc = minetest.formspec_escape

local function chalkboard_edit(pos)
   local meta = minetest.get_meta(pos)
   local title = meta:get_string('infotext')
   local body = meta:get_string('body')
   local formspec =
      'formspec_version[3]'..
      'size[16,9]'..
      'background[0,0;16,9;signs_chalkboard_bg.png]'..
      'field[0.25,.75;15.5,.75;title;Title:;'..esc(title)..']'..
      'textarea[.25,1.75;15.5,5.5;body;;'..esc(body)..']'..
      'button_exit[4.25,7.5;3,1;save;Save]'..
      'button_exit[8.75,7.5;3,1;preview;Preview]'
   return formspec
end

local function chalkboard_read(pos)
   local meta = minetest.get_meta(pos)
   local title = meta:get_string('infotext')
   local body = meta:get_string('body')
   local formspec =
      'formspec_version[3]'..
      'size[16,9]'..
      'background[0,0;16,9;signs_chalkboard_bg.png]'..
      'hypertext[.25,.25;15.5,1.5;;<center><style color=white size=40>'..esc(title)..'</style></center>]'..
      'textarea[.25,1.75;15.5,7;;;'..esc(body)..']'
   return formspec
end

minetest.register_node('signs:chalkboard', {
   description = 'Chalkboard',
   drawtype = 'mesh',
   mesh = 'signs_chalkboard.obj',
   tiles = {'signs_chalkboard.png'},
   paramtype2 = 'facedir',
   paramtype = 'light',
   selection_box = {
      type = 'fixed',
      fixed = {-1, -.75, .4375, 1, .5, .5},
      },
   collision_box = {
      type = 'fixed',
      fixed = {-1, -.75, .4375, 1, .5, .5},
      },
   groups = {breakable=1},
   after_place_node = function(pos, placer)
      local meta = minetest.get_meta(pos)
      meta:set_string('infotext', '')
      meta:set_string('body', '')
   end,
   on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
      local name = clicker:get_player_name()
      if not minetest.is_protected(pos, name) or minetest.check_player_privs(name, { server = true }) then
         signs.player_pos[name] = pos
         minetest.show_formspec(name, 'signs:chalkboard_edit', chalkboard_edit(pos))
      else
         minetest.show_formspec(name, 'signs:chalkboard_read', chalkboard_read(pos))
      end
   end,
})

minetest.register_on_player_receive_fields(function(player, formname, fields)
   if formname == 'signs:chalkboard_edit' then
      local name = player:get_player_name()
      local pos = signs.player_pos[name]
      local meta = minetest.get_meta(pos)
      if fields.save then
         meta:set_string('infotext', fields.title)
         meta:set_string('body', fields.body)
         minetest.log('action', (name or '')..' wrote \''..fields.title..'\' to chalkboard at '..minetest.pos_to_string(pos))
      elseif fields.preview then
         meta:set_string('infotext', fields.title)
         meta:set_string('body', fields.body)
         minetest.log('action', (name or '')..' wrote \''..fields.title..'\' to chalkboard at '..minetest.pos_to_string(pos))
         minetest.show_formspec(name, 'signs:chalkboard_read', chalkboard_read(pos))
      end
   end
end)
