-- This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
-- To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/
-- or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

local MereHealingFrames, privateVars = ...

MereHealingFrames.Config = MereHealingFrames.Config or {}
MereHealingFrames.Config.UI = MereHealingFrames.Config.UI or {}

MereHealingFrames.Config.UI.Buffs = {}
MereHealingFrames.Config.UI.Buffs.buttonTab = {}

function MereHealingFrames.Config.UI.Buffs:new ()
	local this = {}

	setmetatable(this, self)
	self.__index = self
	return this
end


function MereHealingFrames.Config.UI.Buffs:CreateUI (configWindow)

	local BuffSetFrame = {
	getSetList = MereHealingFrames.Config.UI.Buffs.getBuffSetList,	-- table <- nil
	renameSet = MereHealingFrames.BuffSets.RenameSet,	-- nil <- currentName, newName
	addSet = MereHealingFrames.BuffSets.CreateNewBuffSet,		-- nil <- setName
	deleteSet = MereHealingFrames.BuffSets.DeleteBuffSet,	-- nil <- setName
	setSelected = function(...) MereHealingFrames.Config.UI.Buffs.ChangeBuffSetSelection(self, ...) end,	-- nil <- setName
	addButtonText = "Add Buff Set",
	deleteButtonText = "Delete Buff Set",
	renameButtonText = "Rename Buff Set",
	}

	self.Frame = UI.CreateFrame("Frame", "BuffsConfigFrame", configWindow)
	self.Frame:SetPoint("TOPLEFT", configWindow, "TOPLEFT")
	self.Frame:SetPoint("BOTTOMRIGHT", configWindow, "BOTTOMRIGHT")

	self.BuffSets = MereHealingFrames.Config.UI.SetsFrame:new (BuffSetFrame, self:GetContent())
	self.BuffSets:GetContent():SetPoint("TOPLEFT", self:GetContent(), "TOPLEFT")
	self.BuffSets:GetContent():SetPoint("BOTTOMLEFT", self:GetContent(), "BOTTOMLEFT")

	self.BuffSets:CreateUI(self:GetContent())



	self.LayoutTabs = UI.CreateFrame("SimpleTabView", "Config_Tabs", self:GetContent())
	self.LayoutTabs:SetBackgroundColor(0,0,0,0.5)
	self.LayoutTabs:SetPoint("TOPLEFT", self.BuffSets:GetContent(), "TOPRIGHT", 5, 0)
	self.LayoutTabs:SetPoint("BOTTOMRIGHT", self:GetContent(), "BOTTOMRIGHT")

	self:CreateTrackerUI(self.LayoutTabs)

	self.LayoutTabs:AddTab("Trackers", self.TrackerFrame)

	self.SoulSpecs = MereHealingFrames.Config.UI.SoulSpecsTab:new()
	self.SoulSpecs:CreateUI(self.LayoutTabs)
	self.SoulSpecs:SetCallback(function (...) MereHealingFrames.Config.UI.Buffs.SpecChange(self, ...) end)
	self.SoulSpecs:SetText("Pick Soul Specs to associate with this spell set:")

	self.LayoutTabs:AddTab("Soul Specs", self.SoulSpecs:GetContent())

	self.TrackerFrame = UI.CreateFrame("Frame", "BuffsConfigFrame", configWindow)
	self.Frame:SetPoint("TOPLEFT", configWindow, "TOPLEFT")
	self.Frame:SetPoint("BOTTOMRIGHT", configWindow, "BOTTOMRIGHT")



	--self.LayoutTabs:AddTab("Filtering", self:CreateFilteringTab())

	--self.buttonScrollView:SetPoint("BOTTOMRIGHT", self.ButtonFrame, "BOTTOMLEFT", -10, 0)
	--self:RefreshAbilities()

	self.BuffSets:SetSelectedIndex(1)
end


function MereHealingFrames.Config.UI.Buffs:ReloadBuffSetList()
	return self.BuffSets:ReloadSetList()
end

function MereHealingFrames.Config.UI.Buffs.getBuffSetList()
	local items = {}
	for key, layout in pairs(MereHealingFrames.BuffSets.Sets) do
		table.insert(items, key)
	end
	return items
end

function MereHealingFrames.Config.UI.Buffs:ChangeBuffSetSelection(setName)
	if not MereHealingFrames.BuffSets.Sets[setName] then
		return
	end

	self.currentBuffSet = MereHealingFrames.BuffSets.Sets[setName]
	self.SoulSpecs:SetSpecs(self.currentBuffSet.SoulSpecs)
	self.BuffTrackers:ReloadSetList()
end


function MereHealingFrames.Config.UI.Buffs:getBuffTrackerList()
	local trackers = {}
	if self.currentBuffSet == nil or self.currentBuffSet.Trackers == nil then
		return trackers
	end
	for name, _ in pairs(self.currentBuffSet.Trackers) do
		table.insert(trackers, name)
	end

	return trackers
end

function MereHealingFrames.Config.UI.Buffs:RenameBuffTracker(currentName, newName)
	local tracker = self.currentBuffSet.Trackers[currentName]

	if self.currentBuffSet.Trackers[newName] then return false end

	self.currentBuffSet.Trackers[currentName] = nil
	self.currentBuffSet.Trackers[newName] = tracker
	return true
end

function MereHealingFrames.Config.UI.Buffs:CreateNewBuffTracker(setName)
	if self.currentBuffSet.Trackers[setName] then return false end

	self.currentBuffSet.Trackers[setName] = MereHealingFrames.BuffSets.CreateEmptyTracker()
	return true
end

function MereHealingFrames.Config.UI.Buffs:DeleteBuffTracker(trackerName)
	local tracker = self.currentBuffSet.Trackers[trackerName]
	if not tracker then return false end

	self.currentBuffSet.Trackers[trackerName] = nil
end

function MereHealingFrames.Config.UI.Buffs:ChangeBuffTrackerSetSelection(trackerName)
	if not self.currentBuffSet.Trackers[trackerName] then
		return
	end
	local tracker = self.currentBuffSet.Trackers[trackerName]
	self.tracker = tracker
	self:SetupTracker(tracker)
end

function MereHealingFrames.Config.UI.Buffs:SpecChange(specId, newValue)
	if not self.currentBuffSet or not self.currentBuffSet.SoulSpecs then return end

	if newValue then
		MereHealingFrames.BuffSets.ClearSoulSpec(specId)
	end

	self.currentBuffSet.SoulSpecs[specId] = newValue

	if (newValue) then
		self.SoulSpecs:SetSpecs(self.currentBuffSet.SoulSpecs)
		MereHealingFrames.BuffSets.UpdateCurrentSet()
	end
end

function MereHealingFrames.Config.UI.Buffs:GetContent()
	return self.Frame
end

function MereHealingFrames.Config.UI.Buffs:CreateTrackerUI(parentFrame)

	local BuffTrackerSets = {
		getSetList = 	function(...) return MereHealingFrames.Config.UI.Buffs.getBuffTrackerList(self, ...) end,	-- table <- nil
		renameSet = 	function(...) return MereHealingFrames.Config.UI.Buffs.RenameBuffTracker(self, ...) end,	-- nil <- currentName, newName
		addSet = 		function(...) return MereHealingFrames.Config.UI.Buffs.CreateNewBuffTracker(self, ...) end,		-- nil <- setName
		deleteSet = 	function(...) return MereHealingFrames.Config.UI.Buffs.DeleteBuffTracker(self, ...) end,	-- nil <- setName
		setSelected = 	function(...) return MereHealingFrames.Config.UI.Buffs.ChangeBuffTrackerSetSelection(self, ...) end,	-- nil <- setName
		addButtonText = "Add Tracker",
		deleteButtonText = "Delete Tracker",
		renameButtonText = "Rename Tracker",
		}

	self.TrackerFrame = UI.CreateFrame("Frame", "ConfigTrackerFrame", parentFrame)
	self.TrackerFrame:SetPoint("TOPLEFT", parentFrame, "TOPLEFT")
	self.TrackerFrame:SetPoint("BOTTOMRIGHT", parentFrame, "BOTTOMRIGHT")

	self.BuffTrackers = MereHealingFrames.Config.UI.SetsFrame:new (BuffTrackerSets, self.TrackerFrame)
	self.BuffTrackers:GetContent():SetPoint("TOPLEFT", self.TrackerFrame, "TOPLEFT")
	self.BuffTrackers:GetContent():SetPoint("BOTTOMLEFT", self.TrackerFrame, "BOTTOMLEFT")

	self.BuffTrackers:CreateUI()

	self.TrackerUI = {}
	self.TrackerUI.TypeLabel = UI.CreateFrame("Text", "TrackerLabel", self.TrackerFrame)
	self.TrackerUI.TypeLabel:SetPoint("TOPLEFT", self.BuffTrackers:GetContent(), "TOPRIGHT", 5,5)
	self.TrackerUI.TypeLabel:SetText("Tracker Type: ")

	self.TrackerUI.TypeDropDown = UI.CreateFrame("SimpleSelect", "TrackerDropDown", self.TrackerFrame)
	self.TrackerUI.TypeDropDown:SetItems( {"Priority List", "Cleansable counter"}, {"priority", "cleansable"} )
	self.TrackerUI.TypeDropDown:SetPoint("TOPLEFT", self.TrackerUI.TypeLabel, "TOPRIGHT", 20, 0)
	self.TrackerUI.TypeDropDown:SetBorder(1, 1, 1, 1, 1)
	self.TrackerUI.TypeDropDown:ResizeToFit()
    self.TrackerUI.TypeDropDown:SetLayer(11)

	self.TrackerUI.TypeDropDown.Event.ItemSelect = function (item, value, index)  MereHealingFrames.Config.UI.Buffs.TrackerTypeChange(self, index) end

	self.TrackerUI.PriorityFrame = UI.CreateFrame("Frame", "PriorityFrame", self.TrackerFrame)
	self.TrackerUI.PriorityFrame:SetPoint("TOPLEFT", self.TrackerUI.TypeLabel, "BOTTOMLEFT")

	self:CreatePriorityFrame(self.TrackerUI.PriorityFrame)

	self.TrackerUI.BuffSlotTracker = UI.CreateFrame("Frame", "PriorityFrame", self.TrackerFrame)
	self.TrackerUI.BuffSlotTracker:SetPoint("BOTTOMLEFT", self.BuffTrackers:GetContent(), "BOTTOMRIGHT")
	self.TrackerUI.BuffSlotTracker:SetPoint("BOTTOMRIGHT", self.TrackerFrame, "BOTTOMRIGHT")
    self:PopulateBuffSlotsFrame(self.TrackerUI.BuffSlotTracker)

    self.TrackerUI.Description = UI.CreateFrame("Text", "PriorityTrackerDescription", self.TrackerFrame)
    self.TrackerUI.Description:SetWordwrap(true)
    self.TrackerUI.Description:SetText("")
    self.TrackerUI.Description:SetPoint("BOTTOMLEFT", self.TrackerUI.BuffSlotTracker, "TOPLEFT", 5, 0)
    self.TrackerUI.Description:SetPoint("BOTTOMRIGHT", self.TrackerUI.BuffSlotTracker, "TOPRIGHT", -5, 0)

	self.TrackerUI.PriorityFrame:SetPoint("BOTTOMRIGHT", self.TrackerUI.Description, "TOPRIGHT", 5, 0)

end

function MereHealingFrames.Config.UI.Buffs:PopulateBuffSlotsFrame(parentFrame)
	self.BuffSlotTracker = {}

	self.BuffSlotTracker.BuffSlotLabel = UI.CreateFrame("Text", "BuffListLabel", parentFrame)
	self.BuffSlotTracker.BuffSlotLabel:SetPoint("TOPLEFT", parentFrame, "TOPLEFT", 5, 5)
	self.BuffSlotTracker.BuffSlotLabel:SetText("Assigned Buff Slots, these will eventually be matched by config in the layouts, " ..
												"so you can pick which slots an icon uses, currently icons are slots 1-5, with 1 at the top right of a layout: ")
	self.BuffSlotTracker.BuffSlotLabel:SetWordwrap(true)
	self.BuffSlotTracker.BuffSlotLabel:SetPoint("RIGHT", parentFrame, "RIGHT")
	self.BuffSlotTracker.Slots = {}

	local i = 1
	for row=1, 5 do
		for column=1, 4 do
			local checkBox = UI.CreateFrame("SimpleCheckbox", "SpecsBox"..i, parentFrame)

			checkBox:SetPoint("TOPLEFT", self.BuffSlotTracker.BuffSlotLabel, "BOTTOMLEFT", 10+((column - 1)* 100), ((row-1) * 20))
			checkBox:SetText("Buff Slot " .. i)
			checkBox:SetLabelPos("left")
			checkBox.Event.CheckboxChange = function() local slot = column + ((row-1) * 4) MereHealingFrames.Config.UI.Buffs.BuffSlotChange(self, slot) end

			self.BuffSlotTracker.Slots[i] = checkBox
			i = i + 1
		end
    end
    local bottomOffset =  self.BuffSlotTracker.Slots[i-1]:GetBottom()
    local topOffset = parentFrame:GetTop()
    local diff = bottomOffset-topOffset
    MereHealingFrames.Debug(1, "Bottom of last slot is: %d, %d, %d", bottomOffset, topOffset, diff)
    parentFrame:SetHeight(diff)
end

function MereHealingFrames.Config.UI.Buffs:BuffSlotChange(slot)
	MereHealingFrames.BuffSets.ClearBuffSlot(self.currentBuffSet, slot)
	self.tracker.buffSlots[slot] = self.BuffSlotTracker.Slots[slot]:GetChecked()

	MereHealingFrames.BuffSets.UpdateCurrentBuffs()
end

function MereHealingFrames.Config.UI.Buffs:TrackerTypeChange(index)
    self:ChangeTrackerType(index)
	self.tracker.buffType = index

	MereHealingFrames.BuffSets.UpdateCurrentBuffs()
end



function MereHealingFrames.Config.UI.Buffs:CreatePriorityFrame(parentFrame)
	self.TrackerPriorityUI = {}

	self.TrackerPriorityUI.BuffListLabel = UI.CreateFrame("Text", "BuffListLabel", parentFrame)
	self.TrackerPriorityUI.BuffListLabel:SetPoint("TOPLEFT", parentFrame, "TOPLEFT", 5, 5)
	self.TrackerPriorityUI.BuffListLabel:SetText("Buff List: ")

	self.TrackerPriorityUI.BuffListText = MereHealingFrames.Config.UI.Utilities.CreateTextField(parentFrame)
	self.TrackerPriorityUI.BuffListText:SetPoint("TOPLEFT", self.TrackerPriorityUI.BuffListLabel, "TOPLEFT", 120, 0)

	self.TrackerPriorityUI.DebuffListLabel = UI.CreateFrame("Text", "DebuffListLabel", parentFrame)
	self.TrackerPriorityUI.DebuffListLabel:SetPoint("TOPLEFT", self.TrackerPriorityUI.BuffListLabel, "BOTTOMLEFT", 0, 5)
	self.TrackerPriorityUI.DebuffListLabel:SetText("Debuff List: ")

	self.TrackerPriorityUI.DebuffListText = MereHealingFrames.Config.UI.Utilities.CreateTextField(parentFrame)
	self.TrackerPriorityUI.DebuffListText:SetPoint("TOPLEFT", self.TrackerPriorityUI.DebuffListLabel, "TOPLEFT", 120, 0)

	self.TrackerPriorityUI.BuffTypeLabel = UI.CreateFrame("Text", "BuffTypeLabel", parentFrame)
	self.TrackerPriorityUI.BuffTypeLabel:SetPoint("TOPLEFT", self.TrackerPriorityUI.DebuffListLabel, "BOTTOMLEFT", 0, 5)
	self.TrackerPriorityUI.BuffTypeLabel:SetText("Track buffs from: ")

	self.TrackerPriorityUI.BuffTypeDropDown = UI.CreateFrame("SimpleSelect", "TrackerDropDown", parentFrame)
	self.TrackerPriorityUI.BuffTypeDropDown:SetItems( {"only mine", "targets", "anyone"}, {"self", "unit", "any"} )
	self.TrackerPriorityUI.BuffTypeDropDown:SetPoint("TOPLEFT", self.TrackerPriorityUI.BuffTypeLabel, "TOPLEFT", 120, 0)
	self.TrackerPriorityUI.BuffTypeDropDown:SetBorder(1, 1, 1, 1, 1)
	self.TrackerPriorityUI.BuffTypeDropDown:ResizeToFit()
	self.TrackerPriorityUI.BuffTypeDropDown:SetLayer(10)

	self.TrackerPriorityUI.DebuffTypeLabel = UI.CreateFrame("Text", "DebuffTypeLabel", parentFrame)
	self.TrackerPriorityUI.DebuffTypeLabel:SetPoint("TOPLEFT", self.TrackerPriorityUI.BuffTypeLabel, "BOTTOMLEFT", 0, 5)
	self.TrackerPriorityUI.DebuffTypeLabel:SetText("Track debuffs from: ")

	self.TrackerPriorityUI.DebuffTypeDropDown = UI.CreateFrame("SimpleSelect", "TrackerDropDown", parentFrame)
	self.TrackerPriorityUI.DebuffTypeDropDown:SetItems( {"only mine", "targets", "anyone"}, {"self", "unit", "any"} )
	self.TrackerPriorityUI.DebuffTypeDropDown:SetPoint("TOPLEFT", self.TrackerPriorityUI.DebuffTypeLabel, "TOPLEFT", 120, 0)
	self.TrackerPriorityUI.DebuffTypeDropDown:SetBorder(1, 1, 1, 1, 1)
	self.TrackerPriorityUI.DebuffTypeDropDown:ResizeToFit()
	self.TrackerPriorityUI.DebuffTypeDropDown:SetLayer(9)

	self.TrackerPriorityUI.ApplyButton = UI.CreateFrame("RiftButton", "setsApplyButton", parentFrame)
	self.TrackerPriorityUI.ApplyButton:SetPoint("BOTTOMRIGHT", parentFrame, "BOTTOMRIGHT")
	self.TrackerPriorityUI.ApplyButton.Event.LeftClick = function() MereHealingFrames.Config.UI.Buffs.UpdateTracker(self) end
	self.TrackerPriorityUI.ApplyButton:SetText("Apply changes")
end

function MereHealingFrames.Config.UI.Buffs:ChangeTrackerType(newTrackType)
    if newTrackType == "priority" then
        self.TrackerUI.PriorityFrame:SetVisible(true)
        self.TrackerUI.Description:SetText("A priority tracker orders the buff stack by the entered lists, "..
                "it always shows the top most buff.  As buffs drop off the next buff is shown.  " ..
                "Lists should be comma seperated.")
    else
        self.TrackerUI.PriorityFrame:SetVisible(false)
        self.TrackerUI.Description:SetText("A cleansable counter will show how many cleansable debuffs are on the player. " ..
                "It shows the icon of one of the debuffs on the player.  " ..
                "(Note it will eventually show the debuff that will be removed next)")
    end
end

function MereHealingFrames.Config.UI.Buffs:SetupTracker(tracker)
	if tracker == nil then return end
	self.TrackerUI.TypeDropDown:SetSelectedValue(tracker.buffType or "priority", true)

	self:ChangeTrackerType(tracker.buffType)

	self.TrackerPriorityUI.BuffListText:SetText(tracker.buffList or "")
	self.TrackerPriorityUI.DebuffListText:SetText(tracker.debuffList or "")
	self.TrackerPriorityUI.BuffTypeDropDown:SetSelectedValue(tracker.buffCaster or "any", true)
	self.TrackerPriorityUI.DebuffTypeDropDown:SetSelectedValue(tracker.debuffCaster or "any", true)

	for i=1, MereHealingFrames.StaticGlobals.numberOfBuffSlots do
		local value = tracker.buffSlots[i] or false
		local event = self.BuffSlotTracker.Slots[i].Event.CheckboxChange
		self.BuffSlotTracker.Slots[i].Event.CheckboxChange = nil
		self.BuffSlotTracker.Slots[i]:SetChecked(value, true)
		self.BuffSlotTracker.Slots[i].Event.CheckboxChange = event
	end
end

function MereHealingFrames.Config.UI.Buffs:UpdateTracker()
	local tracker = self.tracker

	tracker.buffType = self.TrackerUI.TypeDropDown:GetSelectedValue()
	tracker.buffList = self.TrackerPriorityUI.BuffListText:GetText()
	tracker.debuffList = self.TrackerPriorityUI.DebuffListText:GetText()
	tracker.buffCaster = self.TrackerPriorityUI.BuffTypeDropDown:GetSelectedValue()
	tracker.debuffCaster = self.TrackerPriorityUI.DebuffTypeDropDown:GetSelectedValue()

	MereHealingFrames.BuffSets.UpdateCurrentBuffs()
end