--[[
	Weapon Buttons

	By sarf

	This mod gives you a draggable window with the mainhand / offhand buttons.
	This way you do not have to open the paperdoll to equip weapons anymore.

	Thanks goes to the friendly people on the CosmosUI forums for nagging me
	about fixing it. :)

]]--

-- Options

WeaponButtons_Options = {
	mode = WEAPONBUTTONS_MODE_MELEE;
};

-- Variables

WeaponButtons_Cosmos_Registered = 0;

function WeaponButtons_ToggleMode()
	WeaponButtons_DoToggleMode();
end

function WeaponButtons_ToggleMode_NoChat()
	WeaponButtons_DoToggleMode(true);
end

function WeaponButtons_DoToggleMode(noChat)
	local mode = WeaponButtons_Options.mode;
	if ( mode < WEAPONBUTTONS_MODE_MAX ) then
		mode = mode + 1;
	else
		mode = 1;
	end
	if ( not noChat ) then
		WeaponButtons_Print(format(WEAPONBUTTONS_CHAT_SETMODE, WEAPONBUTTONS_CHAT_MODES[mode]));
	end
	WeaponButtons_ChangeMode(mode);
end

function WeaponButtons_SetDefaultMode(toggle, mode)
	WeaponButtons_ChangeMode(mode);
end

function WeaponButtons_ChangeMode(mode)
	if ( mode ) and ( mode >= WEAPONBUTTONS_MODE_MIN) and ( mode <= WEAPONBUTTONS_MODE_MAX) then
		local obj = nil;
		for k, v in pairs(WeaponButtons_ModesComponents) do
			for key, value in pairs(v) do
				obj = getglobal(value);
				if ( k == mode ) then
					obj:Show();
				else
					obj:Hide();
				end
			end
		end
		WeaponButtons_Options.mode = mode;
	end
end

-- executed on load, calls general set-up functions
function WeaponButtons_OnLoad()
	WeaponButtons_Register();
end

-- registers the mod with the system, integrating it with slash commands and "master" AddOns
function WeaponButtons_Register()
	local name = "WEAPONBUTTONSSLASHENABLE";
	SlashCmdList[name] = WeaponButtons_Main_ChatCommandHandler;
	for k, v in pairs(WEAPONBUTTONS_SLASHCMDS) do
		setglobal("SLASH_"..name..k, v);
	end

	WeaponButtons_Khaos_Register();

	if ( not WeaponButtons_Register_Eclipse() ) then
		if ( TransNUI_RegisterUI ) then
			TransNUI_RegisterUI(WEAPONBUTTONS_FRAMENAME, WEAPONBUTTONS_CONFIG_ECLIPSE_SLASHCMDS, WEAPONBUTTONS_CONFIG_TRANSNUI, WEAPONBUTTONS_CONFIG_TRANSNUI_INFO, 0);
		end
		if ( PopNUI_RegisterUI ) then
			PopNUI_RegisterUI(WEAPONBUTTONS_FRAMENAME, WEAPONBUTTONS_CONFIG_ECLIPSE_SLASHCMDS, WeaponButtons_PopNUICallback, WEAPONBUTTONS_CONFIG_POPNUI, WEAPONBUTTONS_CONFIG_POPNUI_INFO);
		end
	end
	this:RegisterEvent("VARIABLES_LOADED");
end

function WeaponButtons_Extract_NextParameter(msg)
	local params = msg;
	local command = params;
	local index = strfind(command, " ");
	if ( index ) then
		command = strsub(command, 1, index-1);
		params = strsub(params, index+1);
	else
		params = "";
	end
	return command, params;
end



WeaponButtons_Main_ChatCommandHandler_Funcs = nil;

function WeaponButtons_Main_ChatCommandHandler_UpdateFuncs()
	WeaponButtons_Main_ChatCommandHandler_Funcs = {
		{
			cmds = WEAPONBUTTONS_CMDS_TOOLTIP;
			func = WeaponButtons_Toggle_DisplayTooltips;
		},
		{
			cmds = WEAPONBUTTONS_CMDS_LOCK;
			func = WeaponButtons_Toggle_LockPosition;
		},
		{
			cmds = WEAPONBUTTONS_CMDS_MODE;
			func = WeaponButtons_Toggle_DisplayTooltips;
		},
		{
			cmds = WEAPONBUTTONS_CMDS_SHOW;
			func = WeaponButtons_Toggle_Enabled;
		},
	};
end

function WeaponButtons_Func_Mode(commandName, params)
	local modeStr;
	modeStr, params = WeaponButtons_Extract_NextParameter(params);
	local mode = tonumber(modeStr);
	if ( mode ) then
		modeStr = WEAPONBUTTONS_CHAT_MODES[mode];
		if ( modeStr ) then
			WeaponButtons_Print(string.format(WEAPONBUTTONS_CHAT_SETMODE, modeStr));
			if ( strfind( commandName, WEAPONBUTTONS_CMDS_DEFAULT ) ) then
				WeaponButtons_SetDefaultMode(1, mode);
			else
				WeaponButtons_ChangeMode(mode);
			end
		else
			WeaponButtons_Print(WEAPONBUTTONS_CHAT_MODE_ILLEGAL);
		end
	else
		WeaponButtons_Print(WEAPONBUTTONS_CHAT_COMMAND_USAGE);
	end
	return;
end


-- Handles chat - e.g. slashcommands - enabling/disabling the WeaponButtons
function WeaponButtons_Main_ChatCommandHandler(msg)

	local func = nil;

	local toggleFunc = true;

	if ( ( not msg) or ( strlen(msg) <= 0 ) ) then
		WeaponButtons_Print(WEAPONBUTTONS_CHAT_COMMAND_USAGE);
		return;
	end

	if ( not WeaponButtons_Main_ChatCommandHandler_Funcs ) then
		WeaponButtons_Main_ChatCommandHandler_UpdateFuncs();
	end

	local commandName, params = WeaponButtons_Extract_NextParameter(msg);

	if ( ( commandName ) and ( strlen(commandName) > 0 ) ) then
		commandName = string.lower(commandName);
	else
		commandName = "";
	end

	local abort = false;
	for k, v in pairs(WeaponButtons_Main_ChatCommandHandler_Funcs) do
		for key, value in pairs(v.cmds) do
			if ( strfind( commandName, value ) ) then
				func = v.func;
				if ( v.notoggle ) then
					toggleFunc = false;
				end
				abort = true;
				break;
			end
		end
		if ( abort ) then
			break;
		end
	end

	if ( not func ) then
		WeaponButtons_Print(WEAPONBUTTONS_CHAT_COMMAND_USAGE);
		return;
	end

	if ( toggleFunc ) then
		-- Toggle appropriately
		if ( (string.find(params, 'on')) or ((string.find(params, '1')) and (not string.find(params, '-1')) ) ) then
			func(1);
		else
			if ( (string.find(params, 'off')) or (string.find(params, '0')) ) then
				func(0);
			else
				func(-1);
			end
		end
	else
		func(commandName, params);
	end
end


-- Handles events
function WeaponButtons_OnEvent(event)
	if ( event == "VARIABLES_LOADED" ) then
		for k, v in pairs(WEAPONBUTTONS_OPTIONS_DEFAULT) do
			if ( WeaponButtons_Options[k] == nil ) then
				WeaponButtons_Options[k] = v;
			end
		end
		WeaponButtons_UpdateGUIState();
	end
end

function WeaponButtons_UpdateGUIState()
	WeaponButtons_ChangeMode(WeaponButtons_Options.mode);
end

-- Prints out text to a chat box.
function WeaponButtons_Print(msg,r,g,b,frame,id,unknown4th)
	if ( Print ) then
		Print(msg, r, g, b, frame, id, unknown4th);
		return;
	end
	if(unknown4th) then
		local temp = id;
		id = unknown4th;
		unknown4th = id;
	end

	if (not r) then r = 1.0; end
	if (not g) then g = 1.0; end
	if (not b) then b = 1.0; end
	if ( frame ) then
		frame:AddMessage(msg,r,g,b,id,unknown4th);
	else
		if ( DEFAULT_CHAT_FRAME ) then
			DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b,id,unknown4th);
		end
	end
end

function WeaponButton_GetInventoryInfoSlotName(slotName)
	local inventorySlotInfoName = slotName;
	local charIndex = strfind(inventorySlotInfoName, "Character");
	if ( charIndex ) then inventorySlotInfoName = strsub(inventorySlotInfoName, charIndex); end
	inventorySlotInfoName = strsub(inventorySlotInfoName,10);
	return inventorySlotInfoName;
end

function WeaponButtonPaperDollItemSlotButton_OnLoad()
	this:RegisterEvent("UNIT_INVENTORY_CHANGED");
	this:RegisterEvent("ITEM_LOCK_CHANGED");
	this:RegisterEvent("CURSOR_UPDATE");
	this:RegisterEvent("BAG_UPDATE_COOLDOWN");
	this:RegisterEvent("SHOW_COMPARE_TOOLTIP");
	this:RegisterEvent("UPDATE_INVENTORY_ALERTS");
	this:RegisterForDrag("LeftButton");
	this:RegisterForClicks("LeftButtonUp", "RightButtonUp");
	local slotName = this:GetName();
	local id;
	local textureName;

	id, textureName = GetInventorySlotInfo(WeaponButton_GetInventoryInfoSlotName(slotName));

	this:SetID(id);
	local texture = getglobal(slotName.."IconTexture");
	texture:SetTexture(textureName);
	this.backgroundTextureName = textureName;
	PaperDollItemSlotButton_Update();
end

function WeaponButtonPaperDollItemSlotButton_OnUpdate(elapsed)
	if ( GameTooltip:IsOwned(this) ) then
		WeaponButtonPaperDollItemSlotButton_OnEnter();
	end
end


function WeaponButtonPaperDollItemSlotButton_OnEnter()
	if ( WeaponButtons_Options.showTooltips ) then
		if this:GetLeft()<400 then
		  if this:GetTop()<400 then
			  GameTooltip:SetOwner(this,"ANCHOR_RIGHT")
			else
			  GameTooltip:SetOwner(this,"ANCHOR_BOTTOMRIGHT")
			end
		else
		  if this:GetTop()<400 then
			  GameTooltip:SetOwner(this,"ANCHOR_LEFT")
			else
			  GameTooltip:SetOwner(this,"ANCHOR_BOTTOMLEFT")
			end
		end
		local hasItem, hasCooldown, repairCost = GameTooltip:SetInventoryItem("player", this:GetID());
	    if ( not hasItem ) then
			GameTooltip:SetText(TEXT(getglobal(strupper(WeaponButton_GetInventoryInfoSlotName(this:GetName())))));
		end
		if ( hasCooldown ) then
			--this.updateTooltip = TOOLTIP_UPDATE_TIME;
		else
			--this.updateTooltip = nil;
		end
	--	if ( MerchantFrame:IsVisible() ) then
	--		ShowInventorySellCursor(this:GetID());
	--	end
		if ( InRepairMode() and repairCost and (repairCost > 0) ) then
			GameTooltip:AddLine(TEXT(REPAIR_COST), "", 1, 1, 1);
			SetTooltipMoney(GameTooltip, repairCost);
			GameTooltip:Show();
		else
			--CursorUpdate();
		end
	end
end

function WeaponButtons_OnClick(button)
	if ( button == "RightButton" ) then
		WeaponButtons_ToggleMode_NoChat();
	end
end
