-- 
-- Please see the readme.txt file included with this distribution for 
-- attribution and copyright information.
--

function onInit()
	addSourceWithOp("bonus", "+");
	addSource("type");

	super.onInit();
end

function onSourceUpdate()
	local val = calculateSources() + modifier[1];
	if window.type.getState() then
		val = val + NodeManager.getSafeChildValue(window.getDatabaseNode(), "...attackbonus.ranged.total", 0);
	else
		val = val + NodeManager.getSafeChildValue(window.getDatabaseNode(), "...attackbonus.melee.total", 0);
	end
	setValue(val);
end

function getDescriptionString()
	local node = window.getDatabaseNode();

	local attack_text = "[ATTACK";
	local attack_num = tonumber(string.sub(getName(), -1)) or 0;
	if attack_num > 1 then
		attack_text = attack_text .. " #" .. attack_num;
	end
	attack_text = attack_text .. "] ";

	attack_text = attack_text .. window.name.getValue();

	local crit_text = node.getChild("critrange").getValue();
	local dash = string.find(crit_text, "-");
	if dash then
		crit_text = string.sub(crit_text, 1, dash-1);
	end
	local crit_threshold = tonumber(crit_text);
	if not crit_threshold then
		crit_threshold = 20;
	end
	if crit_threshold < 20 then
		attack_text = attack_text .. " [CRIT " .. crit_threshold .. "]";
	end

	return attack_text;
end

function onDrag(button, x, y, draginfo)
	draginfo.setType("attack");
	draginfo.setDieList({ "d20" });
	draginfo.setNumberData(getValue());
	draginfo.setDescription(getDescriptionString());
	draginfo.setShortcutData("charsheet", window.getDatabaseNode().getParent().getParent().getNodeName());

	return true;
end

function onDoubleClick(x,y)
	ChatManager.DoubleClickAction("attack", getValue(), getDescriptionString(), {pc = window.getDatabaseNode().getParent().getParent()});
	return true;
end			
