--[[

    MonkeyBuddy:
    Helps you configure your MonkeyMods.
    
    Website:	www.toctastic.net
	Author:		Trentin
	Email:		monkeymods@gmail.com

--]]

-- *****************************************************************************
-- MonkeyQuest
-- *****************************************************************************

local MonkeyBuddyLocals = {
		sideBarHeight = 0,
	};

local MonkeyBuddyAddOnList = {};


-- global save vars
MonkeyBuddyVars = {};


function MonkeyBuddy_Init()

	MonkeyBuddyTitleBtn_Txt:SetText(MONKEYBUDDY_FRAME_TITLE);

	local MonkeyBuddyDefaults = {
		frameAlpha = {
			default = 255,
			min = 63,
			max = 255,
			step = 1,
			},
		backdropAlpha = {
			default = 255,
			min = 0,
			max = 255,
			step = 1,
			},
	};
	
	-- insert this frame into the blizz list so esc key will close
	tinsert(UISpecialFrames,"MonkeyBuddyFrame");

	-- init the saved vars
	MonkeyAPI_InitMonkeyTable(MONKEYBUDDY_TITLE, MonkeyBuddyDefaults, MonkeyBuddyVars);

	-- register the options with MonkeyBuddy :)
	MonkeyBuddy_CreateOptions(MONKEYBUDDY_TITLE);

	if (DEFAULT_CHAT_FRAME) then
		DEFAULT_CHAT_FRAME:AddMessage(MONKEYBUDDY_LOADED_MSG);
	end
end

function MonkeyBuddy_OnLoad()

    -- register events
    this:RegisterEvent("VARIABLES_LOADED");
    
end

function MonkeyBuddy_OnEvent(event)
    
    if (event == "VARIABLES_LOADED") then

    	MonkeyBuddy_Init();
    end
end

-- create the frames for the monkeymod options
function MonkeyBuddy_CreateOptions(strAddOnName)

	local height = 0;
	local firstFrame = true;
	local newFrame;
	local addOnVars = getglobal(strAddOnName .. "Vars");
	local key;
	local value;
	

	-- create the scroll frame
	local scrollFrame = CreateFrame("ScrollFrame", strAddOnName .. "_MB_ScrollFrame", MonkeyBuddyOptionsContainer, "MonkeyScrollFrame");
	local scrollChild = getglobal(strAddOnName .. "_MB_ScrollFrame_ScrollChild");

	local prevFrame = scrollChild;

	-- boolean vars using checkboxes
	--for key, value in pairs(addOnVars) do
	for key, value in MonkeyAPI_PairsBy_order(addOnVars) do

		if (value.current ~= nil and value.hideFromBuddy ~= true) then

			if (type(value.current) == "boolean") then
			
				-- is it a boolean? if so make a check box

				newFrame = CreateFrame("CheckButton", strAddOnName .. "_" .. key .. "_Check", scrollChild, "MonkeyBuddyCheckButtonTemplate");
		
				getglobal(strAddOnName .. "_" .. key .. "_CheckText"):SetText(getglobal(string.upper(strAddOnName) .. "_" .. key .. "_DESC"));
				
				if (firstFrame == true) then
					newFrame:SetPoint("TOPLEFT", prevFrame, "TOPLEFT", 0, -4);
					firstFrame = false;
				else
					newFrame:SetPoint("TOPLEFT", prevFrame, "BOTTOMLEFT", 0, 4);
				end

				newFrame:SetChecked(value.current);
				
				height = height + newFrame:GetHeight() + 4;
				
				-- make new variables in the checkbox to hold info for the callback later
				newFrame.addon = strAddOnName;
				newFrame.key = tostring(key);

				prevFrame = newFrame;

			end
		end
	end
	
	-- colour vars with colour pickers
	--for key, value in pairs(addOnVars) do
	for key, value in MonkeyAPI_PairsBy_order(addOnVars) do

		if (value.current ~= nil and value.hideFromBuddy ~= true) then

			if (type(value.current) == "table") then
			
			    MonkeyAPI_DebugMsg("colour order: " .. value.order);

				if (value.current.r ~= nil) then

					-- make a colour picker
					newFrame = CreateFrame("Button", strAddOnName .. "_" .. key .. "_ColourBnt", scrollChild, "MonkeyBuddyColourButtonTemplate");

					if (firstFrame == true) then
						newFrame:SetPoint("TOPLEFT", prevFrame, "TOPLEFT", 0, -4);
						firstFrame = false;
					else
						newFrame:SetPoint("TOPLEFT", prevFrame, "BOTTOMLEFT", 0, -4);
					end
					
					height = height + newFrame:GetHeight() + 4;
					
					-- make new variables in the colour picker to hold info for the callback later
					newFrame.addon = strAddOnName;
					newFrame.key = tostring(key);

					getglobal(strAddOnName .. "_" .. key .. "_ColourBnt_Text"):SetText(getglobal(string.upper(strAddOnName) .. "_" .. key .. "_DESC"));
					getglobal(strAddOnName .. "_" .. key .. "_ColourBnt_SwatchTexture"):SetVertexColor(value.current.r, value.current.g, value.current.b);
        			getglobal(strAddOnName .. "_" .. key .. "_ColourBnt_BorderTexture"):SetVertexColor(value.current.r, value.current.g, value.current.b);

					prevFrame = newFrame;
				end
			end
		end
	end

	-- number vars needing a slider
	--for key, value in pairs(addOnVars) do
	for key, value in MonkeyAPI_PairsBy_order(addOnVars) do

		if (value.current ~= nil and value.hideFromBuddy ~= true) then

			if (type(value.current) == "number") then

				if (value.min ~= nil) then

					-- make a slider
					newFrame = CreateFrame("Slider", strAddOnName .. "_" .. key .. "_Slider", scrollChild, "MonkeyBuddySliderTemplate");

					if (firstFrame == true) then
						newFrame:SetPoint("TOPLEFT", prevFrame, "TOPLEFT", 0, -24);
						firstFrame = false;
					else
						newFrame:SetPoint("TOPLEFT", prevFrame, "BOTTOMLEFT", 0, -24);
					end
					
					height = height + newFrame:GetHeight() + 24;
					
					-- make new variables in the slider to hold info for the callback later
					newFrame.addon = strAddOnName;
					newFrame.key = tostring(key);

					
					newFrame:SetMinMaxValues(value.min, value.max);
					newFrame:SetValueStep(value.step);
					newFrame:SetValue(value.current);

					getglobal(strAddOnName .. "_" .. key .. "_SliderText"):SetText(getglobal(string.upper(strAddOnName) .. "_" .. key .. "_DESC"));
					getglobal(strAddOnName .. "_" .. key .. "_SliderLow"):SetText(value.min);
					getglobal(strAddOnName .. "_" .. key .. "_SliderHigh"):SetText(value.max);

					prevFrame = newFrame;
				end
			end
		end
	end
	

	--scrollChild:SetPoint("BOTTOM", scrollFrame, "BOTTOM", 0, newFrame:GetBottom());
	scrollChild:SetHeight(height - 8);
	scrollFrame:UpdateScrollChildRect();
	scrollFrame:Hide();


	table.insert(MonkeyBuddyAddOnList, strAddOnName);

	-- add the addon to the sidebar
	scrollChild = MonkeyBuddySideBarScrollFrame_ScrollChild;
	newFrame = CreateFrame("Button", strAddOnName .. "_MB_SideBar_Button", scrollChild, "MonkeyBuddySideBarButtonTemplate");

	newFrame.addon = strAddOnName;
	newFrame.linkedAddOnFrame = scrollFrame;

	getglobal(strAddOnName .. "_MB_SideBar_Button_Text"):SetText(strAddOnName);
	
	if (table.getn(MonkeyBuddyAddOnList) > 1) then
		-- set the anchor
		newFrame:SetPoint("TOPLEFT", getglobal(MonkeyBuddyAddOnList[table.getn(MonkeyBuddyAddOnList) - 1] .. "_MB_SideBar_Button"), "BOTTOMLEFT", 0, -4);
	end
	
	newFrame:SetPoint("RIGHT", MonkeyBuddySideBarScrollFrame, "RIGHT", 0, -28);

	MonkeyBuddyLocals.sideBarHeight = MonkeyBuddyLocals.sideBarHeight + newFrame:GetHeight() + 4;
	
	scrollChild:SetHeight(MonkeyBuddyLocals.sideBarHeight);
	MonkeyBuddySideBarScrollFrame:UpdateScrollChildRect();

end


-- callback for all checkbuttons
-- this.addon
-- this.key
function MonkeyBuddyCheckButton_OnClick()
    
	local varTable = getglobal(this.addon .. "Vars");

    if (this:GetChecked()) then
		varTable[this.key].current = true;
    else
        varTable[this.key].current = false;
    end
    
    if (getglobal(this.addon .. "_" .. this.key .. "_Changed") ~= nil) then
		getglobal(this.addon .. "_" .. this.key .. "_Changed")();
    end
end

-- callback for all sliders
-- this.addon
-- this.key
function MonkeyBuddySlider_OnValueChanged()

	local varTable = getglobal(this.addon .. "Vars");

    varTable[this.key].current = this:GetValue();

    if (getglobal(this.addon .. "_" .. this.key .. "_Changed") ~= nil) then
		getglobal(this.addon .. "_" .. this.key .. "_Changed")();
    end
    

    -- set the tool tip text
    if (this:GetValue() == floor(this:GetValue())) then
        GameTooltip:SetText(format("%d", this:GetValue()));
    else
        GameTooltip:SetText(format("%.2f", this:GetValue()));
    end
end

-- callback for all colour buttons
function MonkeyBuddyColour_Callback()
	--MonkeyAPI_DebugMsg("MonkeyBuddyColour_Callback() called");
	--MonkeyAPI_DebugMsg(MonkeyBuddyLocals.colourAddon);
	
	local var = getglobal(MonkeyBuddyLocals.colourAddon .. "Vars")[MonkeyBuddyLocals.colourKey].current;

    var.r, var.g, var.b = ColorPickerFrame:GetColorRGB();
    if (var.a ~= nil) then
    	var.a = OpacitySliderFrame:GetValue();
    end
    
    local changedFunc = getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_Changed");
    
    if (changedFunc ~= nil) then
		changedFunc();
    end
    
    -- update the frame in monkeybuddy
    getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_ColourBnt_SwatchTexture"):SetVertexColor(
		var.r, var.g, var.b);
    getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_ColourBnt_BorderTexture"):SetVertexColor(
		var.r, var.g, var.b);
end

-- callback for all colour buttons
function MonkeyBuddyColour_CancelCallback(prevColour)
	--MonkeyAPI_DebugMsg("MonkeyBuddyColour_CancleCallback() called");
	--MonkeyAPI_DebugMsg(MonkeyBuddyLocals.colourAddon);
	
	local var = getglobal(MonkeyBuddyLocals.colourAddon .. "Vars")[MonkeyBuddyLocals.colourKey].current;

    var.r = prevColour.r;
	var.g = prevColour.g;
	var.b = prevColour.b;
	
	if (var.a ~= nil) then
		var.a = prevColour.a;
	end
	
	local changedFunc = getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_Changed");
    
    if (changedFunc ~= nil) then
		changedFunc();
    end
    
    -- update the frame in monkeybuddy
    getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_ColourBnt_SwatchTexture"):SetVertexColor(
		var.r, var.g, var.b);
    getglobal(MonkeyBuddyLocals.colourAddon .. "_" .. MonkeyBuddyLocals.colourKey .. "_ColourBnt_BorderTexture"):SetVertexColor(
		var.r, var.g, var.b);
end

function MonkeyBuddyColourButton_OnClick()

	MonkeyBuddyLocals.colourAddon = this.addon;
	MonkeyBuddyLocals.colourKey = this.key;
	
	local varTable = getglobal(this.addon .. "Vars");

    ColorPickerFrame:SetColorRGB(varTable[this.key].current.r, varTable[this.key].current.g, varTable[this.key].current.b);
    ColorPickerFrame.previousValues = {r = varTable[this.key].current.r, g = varTable[this.key].current.g, b = varTable[this.key].current.b, a = varTable[this.key].current.a};    
	ColorPickerFrame.func = MonkeyBuddyColour_Callback;
	ColorPickerFrame.cancelFunc = MonkeyBuddyColour_CancelCallback;
	if (varTable[this.key].current.a ~= nil) then
		ColorPickerFrame.hasOpacity = true;
		ColorPickerFrame.opacity = varTable[this.key].current.a;
		ColorPickerFrame.opacityFunc = MonkeyBuddyColour_Callback;
	else
		ColorPickerFrame.hasOpacity = false;
	end
	ColorPickerFrame:Show();
end

-- callback for all sidebar buttons
-- this.linkedAddOnFrame
function MonkeyBuddySideBarButton_OnClick()
	
	local key;
	local value;

	for key, value in pairs(MonkeyBuddyAddOnList) do
		
		getglobal(value .. "_MB_ScrollFrame"):Hide();
		getglobal(value .. "_MB_SideBar_Button"):UnlockHighlight();
	end

	this.linkedAddOnFrame:Show();
	this:LockHighlight();

	PlaySound("igMainMenuOptionCheckBoxOn");
end

function MonkeyBuddySideBar_SelectAddOn(strAddOn)
	
	local key;
	local value;

	for key, value in pairs(MonkeyBuddyAddOnList) do
		
		getglobal(value .. "_MB_ScrollFrame"):Hide();
		getglobal(value .. "_MB_SideBar_Button"):UnlockHighlight();
	end

	getglobal(strAddOn .. "_MB_ScrollFrame"):Show();
	getglobal(strAddOn .. "_MB_SideBar_Button"):LockHighlight();

	PlaySound("igMainMenuOptionCheckBoxOn");
end

function MonkeyBuddy_frameAlpha_Changed()

	MonkeyBuddyFrame:SetAlpha(MonkeyBuddyVars.frameAlpha.current / 255);
end

function MonkeyBuddy_backdropAlpha_Changed()

	MonkeyBuddyFrame:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b, MonkeyBuddyVars.backdropAlpha.current / 255);
end

function MonkeyBuddySlider_OnEnter()
    -- put the tool tip in the default position
    GameTooltip:SetOwner(this, "ANCHOR_CURSOR");
    
    -- set the tool tip text
    if (this:GetValue() == floor(this:GetValue())) then
        GameTooltip:SetText(format("%d", this:GetValue()));
    else
        GameTooltip:SetText(format("%.2f", this:GetValue()));
    end
    
    GameTooltip:Show();
end

function MonkeyBuddySlider_OnLeave()
    GameTooltip:Hide();
end
