--
-- OPTIONS SECTION
--
local version = GetAddOnMetadata("TargetForMe", "Version");
local isEnabled = false;			-- default state.
local instanceName = "";			-- The name of the current instance the player is in.
local currentBoss = "";				-- The name of the boss that the macro is currently set for.
local playerStartAttack = true;		-- Will be false for non-melee characters (see onload event).

-- Set-up the command-line handler.
function TargetForMe_OnLoad()
	SlashCmdList["TargetForMe"] = TargetForMe_SlashCmdHandler;
	SLASH_TargetForMe1 = "/tfm";
	-- Hunters don't want to (generally) engage autoshot on targetting! Neither do caster classes.
	-- Shaman is set to still enable auto-attack, rather then implement code to determine spec.
	local localizedClass, englishClass = UnitClass("player");
	if ((englishClass=="HUNTER") or (englishClass=="MAGE") or (englishClass=="WARLOCK") or (englishClass=="PRIEST")) then
		playerStartAttack = false;
	end
end

function TargetForMe_SlashCmdHandler(msgFull)
    local msgTable = {};
    msgTable = TargetForMe_split(msgFull," ");
	TargetForMe_ConsoleMessage("version |cffffff00" .. version .. "|r");
	if (msgTable[1] == "create") then		-- Test routine added as some people having trouble with the mod not creating the macro.
		TargetForMe_ConsoleMessage(TFMtextMessages["Running macro create function!"]);
		local macroIndex = GetMacroIndexByName("TFMTarget");
		if (macroIndex > 0) then
			TargetForMe_ConsoleMessage(TFMtextMessages["Located the TFM macro in slot "] .. macroIndex);
		else
			TargetForMe_ConsoleMessage(TFMtextMessages["No TFM macro located."]);
			local numglobal,numperchar = GetNumMacros();
			TargetForMe_ConsoleMessage(TFMtextMessages["Number of global macros currently in use: "]..numglobal.."/36");
			if (numglobal == 36) then
				TargetForMe_ConsoleMessage(TFMtextMessages["error! You already have the maximum 36 macros allowed. Please delete an existing macro to make room!"]);
			else
				CreateMacro("TFMTarget", 179, TFMBossMacro["test"]);
				TargetForMe_ConsoleMessage(TFMtextMessages["Test macro has been created."]);
			end
		end
		macroIndex = GetMacroIndexByName("TFMcast");
		if (macroIndex > 0) then
		else
			local numglobal,numperchar = GetNumMacros();
			if (numglobal == 36) then
				TargetForMe_ConsoleMessage(TFMtextMessages["error! You already have the maximum 36 macros allowed. Please delete an existing macro to make room!"]);
			else
				CreateMacro("TFMcast", 179, "/cast SPELLNAME");
			end
		end
	elseif (msgTable[1] == "test") then
		TargetForMe_Test();
	else
		TargetForMe_ConsoleMessage(TFMtextMessages["To use, type |cffffff00/macro|r and find the macro |cff00ff00TFMTarget|r"]);
		TargetForMe_ConsoleMessage(TFMtextMessages["Place that macro on an action bar and use it in supported fights to target."]);
		TargetForMe_ConsoleMessage(TFMtextMessages["Use |cffffff00/tfm create|r to create the initial macro."]);
		TargetForMe_ConsoleMessage(TFMtextMessages["To autocast a spell after targetting, edit the |cff00ff00TFMcast|r macro."]);
	end
end

function TargetForMe_OnEvent(self, event, ...)
	if (event == "PLAYER_ENTERING_WORLD") then			-- Fired when the player enters/exits instance.
		local inInstance, instanceType = IsInInstance();
		local name, type, difficultyIndex, difficultyName, maxPlayers, playerDifficulty, isDynamic = GetInstanceInfo();
		instanceName = name;
		if (TFMraidZones[instanceName] == 1) then	-- Player has zoned into a raid instance. Check to see if it's supported.
			isEnabled = true;
			TargetForMe_ConsoleMessage(TFMtextMessages["Instance supported: |cff8080ff"] .. instanceName .. "|r");
		else
			isEnabled = false;
		end
    elseif (event == "UNIT_TARGET") then				-- Someone in your group/raid just changed target.
    	if (isEnabled) then								-- Only check further if we're in a supported instance.
    		if (InCombatLockdown()) then				-- Do nothing if we're in combat.
    		else
    			local unitID = select(1, ...);						-- the unit that just changed target.
    			local targetName = UnitName(unitID .. "target");	-- The name of their target
   				if (targetName == currentBoss) then
   					-- Do nothing if we are already set for this boss.
   				else
	    			if (TFMBossMacro[targetName]) then						-- Unit was targetting an existing boss
	    				currentBoss = targetName;
	    				TargetForMe_ConsoleMessage(TFMtextMessages["Configuring macro for |cffff4040"] .. targetName .. "|r");
    					TargetForMe_SetTargetMacro(TFMBossMacro[targetName]);
	    			end
    			end
    		end
    	else
    	end
    end
end

function TargetForMe_ConsoleMessage(message)
    if (message) then
        print("|cff00ff30TFM:|r " .. message);
    end
end

function TargetForMe_SetTargetMacro(macroText)
	local macroIndex = GetMacroIndexByName("TFMTarget");
	if (playerStartAttack) then
		macroText = macroText .. "/startattack\13";
	end
	macroText = macroText .. TargetForMe_GetCastMacroText();
	if (macroIndex > 0) then
		EditMacro(macroIndex, "TFMTarget", 179, macroText);
	else
		local numglobal,numperchar = GetNumMacros();
		if (numglobal == 36) then
			TargetForMe_ConsoleMessage(TFMtextMessages["error! You already have the maximum 36 macros allowed. Please delete an existing macro to make room!"]);
		else
			CreateMacro("TFMTarget", 179, macroText, nil);
		end
	end
end

-- Look for contents of the TFMcast macro
function TargetForMe_GetCastMacroText()
	local macroIndex = GetMacroIndexByName("TFMcast");
	if (macroIndex > 0) then
		return GetMacroBody(macroIndex);
	else
		return "";
	end
end

function TargetForMe_Test()
	TargetForMe_SetTargetMacro(TFMBossMacro["Lord Jaraxxus"]);
end

-- Taken from http://lua-users.org/wiki/SplitJoin
function TargetForMe_split(str, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
	 table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end