-- This file is provided under the Open Game License version 1.0a
-- For more information on OGL and related issues, see 
--   http://www.wizards.com/d20
--
-- For information on the Fantasy Grounds d20 Ruleset licensing and
-- the OGL license text, see the d20 ruleset license in the program
-- options.
--
-- All producers of work derived from this definition are adviced to
-- familiarize themselves with the above licenses, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- Copyright 2007 SmiteWorks Ltd.


function applyModifierStackToRoll(draginfo)
	if ModifierStack.isEmpty() then
		--[[ do nothing ]]
	elseif draginfo.getNumberData() == 0 and draginfo.getDescription() == "" then
		draginfo.setDescription(ModifierStack.getDescription());
		draginfo.setNumberData(ModifierStack.getSum());
	else
		local originalnumber = draginfo.getNumberData();
		local numstr = tostring(originalnumber);
		if originalnumber > 0 then
			numstr = "+" .. originalnumber;
		end

		local moddesc = ModifierStack.getDescription(true);
		local desc = draginfo.getDescription();
		
		if numstr ~= "0" then
			desc = desc .. " " .. numstr;
		end
		if moddesc ~= "" then
			desc = desc .. " (" .. moddesc .. ")";
		end
		
		draginfo.setDescription(desc);
		draginfo.setNumberData(draginfo.getNumberData() + ModifierStack.getSum());
	end
	
	ModifierStack.reset();
end

function onDiceLanded(draginfo)
	if ChatManager.getDieRevealFlag() then
		draginfo.revealDice(true);
	end

	if draginfo.isType("fullattack") then
		for i = 1, draginfo.getSlotCount() do
			draginfo.setSlot(i);
      local total = 0;
      total = total + ModifierStack.getSum() + draginfo.getNumberData();

			if not ModifierStack.isEmpty() then
				local originalnumber = draginfo.getNumberData();
				local numstr = originalnumber;
				if originalnumber > 0 then
					numstr = "+" .. originalnumber;
				end
				
				draginfo.setStringData(draginfo.getStringData() .. " " .. numstr .. " (" .. ModifierStack.getDescription(true) .. ")");
				draginfo.setNumberData(draginfo.getNumberData() + ModifierStack.getSum());
			end

			local entry = {};
			entry.text = draginfo.getStringData();
			entry.font = "systemfont";
			entry.dice = draginfo.getDieList();
			entry.diemodifier = draginfo.getNumberData();
			
      local dicetable = draginfo.getDieList();
      
      if dicetable then
          for n = 1, table.maxn(dicetable) do
              total = total + dicetable[n].result;
              table.insert(entry.dice, dicetable[n]);
          end

          if dicetable[1].type == "d6" then
              -- If d6 then explode for Wild Die
              if dicetable[1].result == 1 then
                  -- If 1 then remove highest score from remaining dice 
                  -- subtract die value and roll of 1 from total
                  entry.text = entry.text .. "{Échec critique}";
                    
                  local delindex = 0;
                  local maxscore = 0;
                  for i = 2, table.maxn(dicetable) do
                     if dicetable[i].result > maxscore then
                         maxscore = dicetable[i].result;
                         delindex = i;
                     end
                  end

                  if delindex ~= 0 then
                    total = total - 1; -- Remove 1 for roll of 1
                    total = total - dicetable[delindex].result;
                  end
                     
              elseif dicetable[1].result == 6 then
                  -- if 6 then reroll and add score to total
                  entry.text = entry.text .. "{Succès critique}";
                  
                  repeat
                      local reroll = false;
                      local dieRoll = math.random(1, tonumber(string.sub(dicetable[1].type,2)));
                      if dieRoll == 6 then reroll = true; end
                         
                      local explode = {};
                      explode.type = dicetable[1].type;
                      explode.result = dieRoll;
                      table.insert(entry.dice, explode);
                      total = total + dieRoll;
                         
                      local dice = {};
                      table.insert(dice, dicetable[1].type);
                      throwDice("dice", dice, 0, "explode");
                  until not reroll
              end
          end
      end
      
      entry.text = entry.text .. " {Total: " .. total .. "} ";
			
			if User.isHost() then
				if ChatManager.getDieRevealFlag() then
					entry.dicesecret = false;
				end
				entry.sender = GmIdentityManager.getCurrent();
			else
				entry.sender = User.getIdentityLabel();
			end
			
			deliverMessage(entry);
		end
		
		ModifierStack.reset();
		return true;
	elseif draginfo.isType("dice") then
    -- Normal Die Rolls
    if draginfo.getDescription() == "explode" then return true end;
        
    local total = 0;
    total = total + ModifierStack.getSum() + draginfo.getNumberData();
    applyModifierStackToRoll(draginfo);
    
    -- Die Roll Processing
    -- explode on 1 or 6 thrown on d6
    for i = 1, draginfo.getSlotCount() do
        draginfo.setSlot(i);
        
        local entry = {};
        entry.text = draginfo.getDescription();
        entry.font = "systemfont";
        entry.dice = {};
        entry.diemodifier = draginfo.getNumberData();
        local dicetable = draginfo.getDieList();
        
        if dicetable then
            for n = 1, table.maxn(dicetable) do
                total = total + dicetable[n].result;
                table.insert(entry.dice, dicetable[n]);
            end
  
            if dicetable[1].type == "d6" then
                -- If d6 then explode for Wild Die
                if dicetable[1].result == 1 then
                    -- If 1 then remove highest score from remaining dice 
                    -- subtract die value and roll of 1 from total
                    entry.text = entry.text .. "{Échec critique}";
                    
                    local delindex = 0;
                    local maxscore = 0;
                    for i = 2, table.maxn(dicetable) do
                       if dicetable[i].result > maxscore then
                           maxscore = dicetable[i].result;
                           delindex = i;
                       end
                    end
  
                    if delindex ~= 0 then
                      total = total - 1; -- Remove 1 for roll of 1
                      total = total - dicetable[delindex].result;
                    end
                    
                elseif dicetable[1].result == 6 then
                    -- if 6 then reroll and add score to total
                    entry.text = entry.text .. "{Succès critique}";
                    
                    repeat
                        local reroll = false;
                        local dieRoll = math.random(1, tonumber(string.sub(dicetable[1].type,2)));
                        if dieRoll == 6 then reroll = true; end
                           
                        local explode = {};
                        explode.type = dicetable[1].type;
                        explode.result = dieRoll;
                        table.insert(entry.dice, explode);
                        total = total + dieRoll;
                           
                        local dice = {};
                        table.insert(dice, dicetable[1].type);
                        throwDice("dice", dice, 0, "explode");
                    until not reroll
                end
            end
        end
        
        entry.text = entry.text .. " {Total: " .. total .. "} ";
        
        if User.isHost() then
            if ChatManager.getDieRevealFlag() then
               entry.dicesecret = false;
            end
            entry.sender = GmIdentityManager.getCurrent();
        else
            entry.sender = User.getIdentityLabel();
        end
         
        deliverMessage(entry);
    end
    
		ModifierStack.reset();
    return true;
	end
end

function onDrop(x, y, draginfo)
	if draginfo.getType() == "number" then
		applyModifierStackToRoll(draginfo);
	end
end

function moduleActivationRequested(module)
	local msg = {};
	msg.text = "Players have requested permission to load '" .. module .. "'";
	msg.font = "systemfont";
	msg.icon = "indicator_moduleloaded";
	addMessage(msg);
end

function moduleUnloadedReference(module)
	local msg = {};
	msg.text = "Could not open sheet with data from unloaded module '" .. module .. "'";
	msg.font = "systemfont";
	addMessage(msg);
end

function onInit()
	ChatManager.registerControl(self);
	
	if User.isHost() then
		Module.onActivationRequested = moduleActivationRequested;
	end

	Module.onUnloadedReference = moduleUnloadedReference;
end

function onClose()
	ChatManager.registerControl(nil);
end

function onInit()
	ChatManager.registerControl(self);
	
	if User.isHost() then
		Module.onActivationRequested = moduleActivationRequested;
		-- Info Version Grimmbart
		ChatManager.GrimmVersion();
	else
		-- Info Version Grimmbart
		ChatManager.GrimmVersion();
		-- Info sur Aide
		local msg = {};		
		msg.font = "systemfont";	
		msg.text = "";
		deliverMessage(msg);
		--		
		msg.text = "";
		deliverMessage(msg);
		msg.text = "Pour affficher l'aide, tapez la commande /";		
		deliverMessage(msg);
		msg.text = "";	
		deliverMessage(msg);
	end

	Module.onUnloadedReference = moduleUnloadedReference;
end

function onClose()
	ChatManager.registerControl(nil);
end

-- Custom: the_box
function onReceiveMessage(msg)
	if not User.isHost() then
		return false;
	elseif msg.sender ~= "thebox_box_roll:" then
		return false;
	else
		ChatManager.processDie(msg.text);
		return true;
	end
end
-- End Custom: the_box