-- INTERACTIONS.LUA (for Minetest)

-- CONTEXTUAL STUFF
-- ================

-- _contexts to enable passing across formspecs
-- https://rubenwardy.com/minetest_modding_book/en/players/formspecs.html#contexts

local _contexts = {}
local function get_context(name)
    local context = _contexts[name] or {}
    _contexts[name] = context
    return context
end
minetest.register_on_leaveplayer(function(player)
    _contexts[player:get_player_name()] = nil
end)

-- UTILITIES
-- =========

-- Function: formspec_list
-- for use generating option lists in formspecs from tables
-- input: table of strings
-- output: a formspec-ready list of the strings
local function formspec_list(array)
   local escaped = {}
   if not array then
      return ""
   end
   for i = 1, #array do
      escaped[i] = minetest.formspec_escape(array[i])
   end
   return table.concat(escaped,",")
end

-- DASHBOARDS
-- ==========

-- Function: modpol.interactions.dashboard(user)
-- Params: user (string)
-- Q: Should this return a menu of commands relevant to the specific user?
-- Output: Displays a menu of commands to the user
-- TODO currently a manually curated list---needs major improvement
function modpol.interactions.dashboard(user)
   -- prepare data
   -- to add: nested orgs map
   local all_orgs = modpol.orgs.list_all()
   local user_orgs = modpol.orgs.user_orgs(user)
   local all_users = modpol.instance:list_members()
   -- pending list
   local user_pending = {"View..."}
   local user_pending_count = 0
   for k,v in ipairs(modpol.orgs.array) do
      if v.pending and v.pending[user] then
         modpol.msg(v.name)
         table.insert(user_pending, v.name)
         user_pending_count = user_pending_count + 1
      end
   end

   -- set up formspec
    local formspec = {
       "formspec_version[4]",
       "size[10,8]",
       "label[0.5,0.5;M O D P O L]",
       "label[0.5,2;All orgs:]",
       "dropdown[2,1.5;7,0.8;all_orgs;"..formspec_list(all_orgs)..";;]",
       "label[0.5,3;Your orgs:]",
       "dropdown[2,2.5;7,0.8;user_orgs;"..formspec_list(user_orgs)..";;]",
       "label[0.5,4;All users:]",
       "dropdown[2,3.5;7,0.8;all_users;"..formspec_list(all_users)..";;]",
       "label[0.5,5;Pending ("..user_pending_count.."):]",
       "dropdown[2,4.5;7,0.8;pending;"..formspec_list(user_pending)..";;]",
       "button[0.5,7;1,0.8;refresh;Refresh]",
       "button_exit[8.5,7;1,0.8;close;Close]",
    }
    local formspec_string = table.concat(formspec, "")
    -- present to player
    minetest.show_formspec(user, "modpol:dashboard", formspec_string)
end
-- receive input
minetest.register_on_player_receive_fields(function (player, formname, fields)
      if formname == "modpol:dashboard" then
         local pname = player:get_player_name()
         if nil then
         elseif fields.close then
            minetest.close_formspec(pname, formname)
         elseif fields.refresh then
            modpol.interactions.dashboard(pname)
         -- Put all dropdowns at the end
         elseif fields.all_orgs or fields.user_orgs or fields.pending then
            local org_name = fields.all_orgs or fields.user_orgs or fields.pending
            modpol.interactions.org_dashboard(pname, org_name)
         end
      end
end)


-- Function: modpol.interactions.org_dashboard
-- Params: user (string), org_string (string or num)
-- Output: Displays a menu of org-specific commands to the user
function modpol.interactions.org_dashboard(user, org_string)
   -- prepare data
   local org = modpol.orgs.get_org(org_string)
   if not org then return nil end

   local function membership_toggle(org_display)
      local current_org = modpol.orgs.get_org(org_display)
      if current_org then
         if current_org:has_member(user) then
            return " (member)"
         end
      end
      return ""
   end
   
   -- identify parent
   local parent = modpol.orgs.get_org(org.parent)
   if parent then parent = parent.name
   else parent = "none" end

   -- prepare children menu
   local children = {}
   for k,v in ipairs(org.children) do
      local this_child = modpol.orgs.get_org(v)
      table.insert(children, this_child.name)
   end
   table.sort(children)
   table.insert(children,1,"View...")

   -- prepare modules menu
   local modules = {}
   if org.modules then
      for k,v in pairs(org.modules) do
         if not v.hide then -- hide utility modules
            local module_entry = v.name
            table.insert(modules, module_entry)
         end
      end
   end
   table.sort(modules)
   table.insert(modules,1,"View...")

   -- prepare pending menu
   local pending = {}
   local num_pending = 0
   if org.pending[user] then
      for k,v in pairs(org.pending[user]) do
         local pending_string = org.processes[k].name
            .." ["..k.."]"
         table.insert(pending, pending_string)
         num_pending = num_pending + 1
      end
   end
   table.sort(pending)
   table.insert(pending,1,"View...")

   -- set player context
   local user_context = {}
   user_context["current_org"] = org.name
   _contexts[user] = user_context
   -- set up formspec
    local formspec = {
       "formspec_version[4]",
       "size[10,8]",
       "label[0.5,0.5;Org: "..
          minetest.formspec_escape(org.name)..membership_toggle(org.name).."]",
       "label[0.5,1;Parent: "..parent..membership_toggle(parent).."]",
       "label[0.5,2;Members:]",
       "dropdown[2,1.5;7,0.8;user_orgs;"..formspec_list(org.members)..";;]",
       "label[0.5,3;Children:]",
       "dropdown[2,2.5;7,0.8;children;"..formspec_list(children)..";;]",
       "label[0.5,4;Modules:]",
       "dropdown[2,3.5;7,0.8;modules;"..formspec_list(modules)..";;]",
       "label[0.5,5;Pending ("..num_pending.."):]",
       "dropdown[2,4.5;7,0.8;pending;"..formspec_list(pending)..";;]",
       "button[0.5,7;1,0.8;refresh;Refresh]",
       "button[8.5,7;1,0.8;back;Back]",
    }
    local formspec_string = table.concat(formspec, "")
    -- present to player
    minetest.show_formspec(user, "modpol:org_dashboard", formspec_string)
end
-- receive input
minetest.register_on_player_receive_fields(function (player, formname, fields)
      if formname == "modpol:org_dashboard" then
         local pname = player:get_player_name()
         local org = modpol.orgs.get_org(_contexts[pname].current_org)
         -- just confirm the org still exists:
         if not org then
            modpol.interactions.message(pname, "Org no longer exists")
            modpol.interactions.dashboard(pname)
            return end
         -- okay, onward
         if nil then
         elseif fields.back then
            modpol.interactions.dashboard(pname)
         elseif fields.refresh then
            modpol.interactions.org_dashboard(pname,org.name)
            
         -- Put all dropdowns at the end
         -- Receiving modules
         elseif fields.modules
            and fields.modules ~= "View..." then
            local module = nil
            for k,v in pairs(org.modules) do
               if fields.modules == v.name then
                  module = v
            end end
            if module then
               modpol.interactions.binary_poll_user(
                  pname,
                  module.name..":\n"..
                  module.desc.."\n"..
                  "Proceed?",
                  function(input)
                     if input == "Yes" then
                        org:call_module(module.slug, pname)
                     end
               end)
            end
            
         -- Receiving pending
         elseif fields.pending
            and fields.pending ~= "View..." then
            local pending = string.match(
               fields.pending,"%[(%d)%]")
            local process = org.processes[tonumber(pending)]
            if process then
               org:interact(process.id, pname)
            end

         -- Children
         elseif fields.children
               and fields.children ~= "View..." then
            local org_name = fields.children
            modpol.interactions.org_dashboard(pname, org_name)
         end
      end
end)


-- Function: modpol.interactions.policy_dashboard
-- input: user (string), org_id (int), policy (string)
-- output: opens a dashboard for viewing/editing policy details
-- TODO
function modpol.interactions.policy_dashboard(
      user, org_id, policy)
   modpol.interactions.message(
      user,
      "Not yet implemented: " .. policy)
end


-- INTERACTION FUNCTIONS
-- =====================

-- Function: modpol.interactions.message
-- input: user (string), message (string)
-- output: displays message to specified user
function modpol.interactions.message(user, message)
   if message then
      minetest.chat_send_player(user, message)
   end
end

-- Function: modpol.interactions.text_query
-- Overrides function at modpol/interactions.lua
-- input: user (string), query (string), func (function)
-- output: Applies "func" to user input
function modpol.interactions.text_query(user, query, func)
   -- set up formspec
    local formspec = {
       "formspec_version[4]",
       "size[10,4]",
       "label[0.5,1;", minetest.formspec_escape(query), "]",
       "field[0.5,1.25;9,0.8;input;;]",       
       "button[0.5,2.5;1,0.8;yes;OK]",
    }
    local formspec_string = table.concat(formspec, "")
    -- present to player
    minetest.show_formspec(user, "modpol:text_query", formspec_string)
    -- put func in _contexts
    if _contexts[user] == nil then _contexts[user] = {} end
    _contexts[user]["text_query_func"] = func
end
-- receive fields
minetest.register_on_player_receive_fields(function (player, formname, fields)
      if formname == "modpol:text_query" then
         local pname = player:get_player_name()
         local input = fields.input
         if not input then
            -- no input, do nothing
         else
            local func = _contexts[pname]["text_query_func"]
            if func then
               func(input)
            else
               modpol.interactions.message(pname, "text_query: " .. input)
            end
         end
         minetest.close_formspec(pname, formname)
      end
end)

-- Function: dropdown_query
-- input: user (string), label (string), options (table of strings), func (function)
--    func input: choice (string)
-- output: calls func on user choice
function modpol.interactions.dropdown_query(user, label, options, func)
   -- Add "View..." to the top of the list
   table.insert(options,1,"View...")
   -- set up formspec
   local formspec = {
      "formspec_version[4]",
      "size[10,4]",
      "label[0.5,1;"..minetest.formspec_escape(label).."]",
      "dropdown[0.5,1.25;9,0.8;input;"..formspec_list(options)..";;]",
      "button[0.5,2.5;1,0.8;cancel;Cancel]",
   }
   local formspec_string = table.concat(formspec, "")
   -- present to players
   minetest.show_formspec(user, "modpol:dropdown_query", formspec_string)
   -- put func in _contexts
   if _contexts[user] == nil then _contexts[user] = {} end
   _contexts[user]["dropdown_query_func"] = func
end
-- receive fields
minetest.register_on_player_receive_fields(function (player, formname, fields)
      if formname == "modpol:dropdown_query" then
         local pname = player:get_player_name()            
         if fields.cancel then
            minetest.close_formspec(pname, formname)
         elseif fields.input == "View..." then
            -- "View...", do nothing
         else
            local choice = fields.input
            local func = _contexts[pname]["dropdown_query_func"]
            if not choice then
               -- empty, do nothing
            elseif func then
               --causes issues with sequential dropdowns
               --minetest.close_formspec(pname, formname)
               func(choice)
            else
               minetest.close_formspec(pname, formname)
               modpol.interactions.message(pname, "dropdown_query: " .. choice)
            end
         end
      end
end)

-- Function: modpol.binary_poll_user(user, question, function)
-- Overrides function at modpol/interactions.lua
-- Params: user (string), question (string), func (function)
--   func input: user input (string: y/n)
-- Output: Applies "func" to user input
function modpol.interactions.binary_poll_user(user, question, func)
   -- set up formspec
   local formspec = {
      "formspec_version[4]",
      "size[8,4]",
      "label[0.375,0.5;",minetest.formspec_escape(question), "]",
      "button[1,2.5;1,0.8;yes;Yes]",
      "button[2,2.5;1,0.8;no;No]",
      --TODO can we enable text wrapping?
      --TODO we could use scroll boxes to contain the text
   }
   local formspec_string = table.concat(formspec, "")
   if _contexts[user] == nil then _contexts[user] = {} end
   _contexts[user]["binary_poll_func"] = func
   -- present to player
   minetest.show_formspec(user, "modpol:binary_poll_user", formspec_string)
end
minetest.register_on_player_receive_fields(function (player, formname, fields)
      local pname = player:get_player_name()
      -- modpol:binary_poll
      if formname == "modpol:binary_poll_user" then
         local vote = nil
         if fields.yes then vote = fields.yes
         elseif fields.no then vote = fields.no
         end
         if vote then
            local func = _contexts[pname]["binary_poll_func"]
            if func then func(vote) end
         end
         minetest.close_formspec(pname, formname)
      end
end)