StupidMount2_Options = {};

function StupidMount2_OnLoad()
	StupidMount2Tooltip:SetOwner(StupidMount2Tooltip, "ANCHOR_NONE");
	StupidMount2_Options_OnLoad();
	
	local f = StupidMount2Frame;
	f:RegisterEvent("VARIABLES_LOADED");
	f:RegisterEvent("UI_ERROR_MESSAGE");
end


-- Lots of credits to IsMounted code for this one!
function StupidMount2_GetMountBuffIndex()
	if (IsMounted()) then
		local text;
		for i = 1, 24 do
			local buffIndex, untilCancelled = GetPlayerBuff(i, "HELPFUL|PASSIVE");
			-- TODO: this may be changed in some patch, far far away
			if ( buffIndex == 0 ) then
				return;
			end
			if ( untilCancelled ) and ( buffIndex >= 0 ) then
				StupidMount2Tooltip:SetPlayerBuff(buffIndex);
				if (StupidMount2TooltipTextLeft2:IsShown()) then
					text = StupidMount2TooltipTextLeft2:GetText();
					if (text) then
						local _, _, speed = strfind(text, STUPIDMOUNT2_TOOLTIP_GFIND_PATTERN);
						if (speed) then
							return buffIndex;
						end
					end
				end
			end
		end
	end
	return nil;
end

function StupidMount2_HandleDismount()
	if ( UnitOnTaxi("player") ) then
		return;
	end
	if ( not StupidMount2_Options.enabled ) then
		return;
	end
	if ( not StupidMount2_Options.dismountInCombat ) and ( PlayerFrame.inCombat ) then
		return;
	end
	if (Dismount) then
		Dismount();
	else
		local index = StupidMount2_GetMountBuffIndex();
		if ( index ) then
			CancelPlayerBuff(index);
		end
	end
end

function StupidMount2_OnEvent(event, msg)
	if ( event == "VARIABLES_LOADED" ) then
		for k, v in pairs( STUPIDMOUNT2_OPTIONS_DEFAULT ) do
			if ( StupidMount2_Options[k] == nil ) then
				StupidMount2_Options[k] = v;
			end
		end
		
	elseif ( event == "UI_ERROR_MESSAGE" ) then
		if ( msg == SPELL_FAILED_NOT_MOUNTED ) then
			StupidMount2_HandleDismount();
			
		elseif ( msg == ERR_TAXIPLAYERALREADYMOUNTED ) then
			StupidMount2_HandleDismount();
		end
	end
end

