

local function createSpacer(width)
	local label = WhatsNext.AceGUI:Create('Label');
	label:SetText(" ");
	if width <= 0 then
		label:SetFullWidth(true)
	else
		label:SetWidth(width)
	end
	return label
end

local function UpdateToolTip()
	local frame = WhatsNext.entryFrame;
	local scale = GameTooltip:GetEffectiveScale();
	
	--frame.tooltip:ClearAllPoints();				
	local type = frame.entry.type;
	local value = frame.entry[type];
	frame.tooltip:ClearLines()
	if type == "spell" and value and tonumber(value) then
		local icon = select(3,GetSpellInfo(value))
		frame.icon:SetNormalTexture(icon);
		frame.tooltip:SetSpellByID(value)
		frame.tooltip:Show()
	elseif type == "item" then
		local icon = select(10,GetItemInfo(value))
		frame.icon:SetNormalTexture(icon);
		frame.tooltip:SetItemByID(value)
		frame.tooltip:Show()
	elseif type == "note" then
		frame.icon:SetNormalTexture(WhatsNext.ICON_QUESTION_MARK);
		frame.tooltip:SetText("Note")
		frame.tooltip:AddLine(value,1,1,1)
		frame.tooltip:Show()
	elseif type == "macro" then
		local icon = select(2,GetMacroInfo(value))
		frame.icon:SetNormalTexture(icon);
		frame.tooltip:SetText("Macro")
		frame.tooltip:AddLine(GetMacroBody(value),1,1,1)
		frame.tooltip:Show()
	else
	--	frame.tooltip:Hide()
	end
	

end

local function onActionChange(dropdown,event,value)  
	local frame = WhatsNext.entryFrame;
	frame.entry[frame.entry.type] = value;
	UpdateToolTip()		
end

local function onActionTypeChange(dropdown,event,value)
	local frame = WhatsNext.entryFrame;
	frame.entry.type = value;
	if value == "spell" then
		frame.actionNameLabel:SetText("Spell Name:")
		local spellBook = WhatsNext:GetSpellBook(0);
		local spellList = {}
		local spellPairs = {}
		local spellOrder = {}
		for id,spell in pairs(spellBook) do
			--print(spell.name, spell.isPassive, spell.specIndex)
			if not spell.isPassive then 
				spellList[id] = spell.name;
				tinsert(spellPairs,{id,0,spell.name});
				
			end
		end
		spellBook = WhatsNext:GetSpellBook(GetSpecialization());
		for id,spell in pairs(spellBook) do
			--print(spell.name, spell.isPassive, spell.specIndex)
			if not spell.isPassive then
				spellList[id] = spell.name;
				tinsert(spellPairs,{id,1,spell.name});
			end
		end
		table.sort(spellPairs,function(v1,v2) 
			if v1[2] ~= v2[2] then
				return v1[2] < v2[2]
			end
			return v1[3] < v2[3]
		end)
		
		local oldSpell;
		for i,spell in ipairs(spellPairs) do
			if spell[1] == frame.entry['spell'] then
				oldSpell = spell[1]
			end
			tinsert(spellOrder,spell[1]);
		end
		frame.valueDropdown:SetList(spellList,spellOrder)
		frame.valueDropdown:SetValue(oldSpell or spellOrder[1])
	elseif value=="item" then
		frame.actionNameLabel:SetText("Item Name:")
		local itemPairs = {}
		local itemList = {}
		local itemOrder = {}
		local bagSize
		for bag = 0, NUM_BAG_SLOTS do
			bagSize = GetContainerNumSlots(bag);
			if bagSize > 0 then
				for i = 1, bagSize do
					local itemId = GetContainerItemID(bag, i)
					if itemId then
						local itemName = GetItemInfo(itemId) 
						local itemSpell, itemSpellId = GetItemSpell(itemId)
						if itemSpellId then
							itemList[itemId] = itemName
							tinsert(itemPairs,{itemId,itemName});
						end
					end
				end
			end
		end
		for i = 1,20 do 
			local itemId = GetInventoryItemID("player", i)
			if itemId then
				local itemName = GetItemInfo(itemId) 
				local itemSpell, itemSpellId = GetItemSpell(itemId)
				if itemSpellId then
					itemList[itemId] = itemName
					tinsert(itemPairs,{itemId,itemName});
				end
			end
		end
		
		table.sort(itemPairs,function(v1,v2) 
			return v1[2] < v2[2]
		end)
		
		local oldItem;
		for i,item in ipairs(itemPairs) do
			tinsert(itemOrder,item[1]);
			if item[1] == frame.entry['item'] then
				oldItem = item[1]
			end
		end
		frame.valueDropdown:SetList(itemList,itemOrder)
		frame.valueDropdown:SetValue(oldItem or itemOrder[1])
	elseif value=="macro" then
		frame.actionNameLabel:SetText("Macro Name:")
	
		local macroList = {}
		local macroOrder = {}
		local oldMacro;
		local NUM_MACRO = GetNumMacros()
		for i = 1, NUM_MACRO do
			local name, iconTexture, body, isLocal = GetMacroInfo(i);
			macroList[name] = name;
			macroOrder[i] = name
			if name == frame.entry['macro'] then
				oldMacro = name
			end
		end
		table.sort(macroOrder)
		frame.valueDropdown:SetList(macroList,macroOrder)
		frame.valueDropdown:SetValue(oldMacro or macroOrder[1])
	end
	onActionChange(frame.valueDropdown,nil,frame.valueDropdown:GetValue())
end

local function UpdateSelectedCondition()
	local selected = WhatsNext.entryFrame.conditionsScrollFrame.selected;
	for i,checkLabel in ipairs(WhatsNext.entryFrame.conditionsScrollFrame.conditionLabels) do
		if i ==selected then
			checkLabel.bg:SetColorTexture(.2,.2,.2,1)
		else
			checkLabel.bg:SetColorTexture(0,0,0,0)
		end
	end
	local noSelected = not selected or selected == 0
	WhatsNext.entryFrame.editConditionButton:SetDisabled(noSelected)
	WhatsNext.entryFrame.removeConditionButton:SetDisabled(noSelected)
	
end

local function UpdateConditionsContainer()
	local frame = WhatsNext.entryFrame;
	if frame.conditionsScrollFrame.conditionLabels then
		for i,checkLabel in ipairs(WhatsNext.entryFrame.conditionsScrollFrame.conditionLabels) do
			checkLabel.bg:SetColorTexture(0,0,0,0)
			checkLabel.btn:Hide()
		end
	end

	
	frame.conditionsScrollFrame:ReleaseChildren();
	frame.conditionsScrollFrame.conditionLabels = {}
	frame:PauseLayout()
	for i,check in ipairs(frame.entry.checks) do
		local checkLabel = WhatsNext.AceGUI:Create('InteractiveLabel');
		checkLabel:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
		checkLabel:SetFullWidth(true)
		checkLabel.index = i;
		checkLabel:SetText(WhatsNext:GetCheckText(check));
		
		if not checkLabel.bg then
			checkLabel.bg = checkLabel.frame:CreateTexture(nil, "BACKGROUND")
			checkLabel.bg:SetColorTexture(0,0,0,0)
			checkLabel.bg:SetAllPoints()
		end
		
		if not checkLabel.btn then
			checkLabel.btn = CreateFrame("Button","blockCheckButton"..i,checkLabel.frame)
			checkLabel.btn:SetAllPoints()
			
			checkLabel.btn:SetScript('OnClick', function(self, button, down)	
				frame.conditionsScrollFrame.selected = self.index;
				UpdateSelectedCondition()
			end);
			checkLabel.btn:SetScript('OnDoubleClick', function(self, button, down)	
				frame.conditionsScrollFrame.selected = self.index;
				WhatsNext:ShowConditionFrame(self.index,frame.entry.checks[self.index],function(condition,index)
					if index and index >0 then
						frame.entry.checks[index] = condition;
					else
						tinsert(frame.entry.checks,condition);
					end
					WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
					UpdateConditionsContainer()
				end,function()
					WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
				end)
				frame.frame:Hide()
			end);
		end
		
		checkLabel.btn:Show()
		checkLabel.btn.index = i
		frame.conditionsScrollFrame:AddChild(checkLabel);
		frame.conditionsScrollFrame.conditionLabels[i] = checkLabel;
	end
	frame:ResumeLayout()
	frame:DoLayout()
	
	UpdateSelectedCondition()
end

function WhatsNext:ShowEntryFrame(isNew,sourceIndex, entry,confirmFunction,cancelFunction)
	if not self.entryFrame then
		local frame = self.AceGUI:Create("Window")
		_G["WhatsNext_EntryFrame"] = frame
		frame:PauseLayout()
		
		frame.class = select(2,UnitClass("player"));
		frame.spec =  GetSpecialization() or 1
		
		WhatsNext_AddOptionsScreen(frame.frame)
		tinsert(UISpecialFrames, "WhatsNext_EntryFrame") 
		self.entryFrame = frame
		frame:SetWidth(750)
		frame:SetHeight(300)
		frame:SetTitle("What's Next? - Entry Editor")
		frame:SetStatusText("")
		frame:EnableResize(false);
		frame:SetLayout("Flow")
		frame:SetAutoAdjustHeight(false)
		
		
		frame.frame.texture = frame.frame:CreateTexture(nil, "BACKGROUND")
		frame.frame.texture:SetColorTexture(0,0,0,1)
		frame.frame.texture:SetPoint("TOPLEFT",frame.frame,"TOPLEFT",8,-8)
		frame.frame.texture:SetPoint("BOTTOMRIGHT",frame.frame,"BOTTOMRIGHT",-6,8)

		frame.typeLabel = WhatsNext.AceGUI:Create('Label');
		frame.typeLabel:SetText("Action Type:");
		frame.typeLabel:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
		frame.typeLabel:SetWidth(139)
		frame.typeLabel.label:SetJustifyH("RIGHT")		
		
		frame.tooltip = CreateFrame( "GAMETOOLTIP", "WhatsNext_Entry_TargetToolip", frame.frame, "GameTooltipTemplate" ); 
		frame.tooltip:SetOwner( frame.frame, "ANCHOR_NONE" );
		frame.tooltip:SetPoint("TOPLEFT",frame.frame,"TOPRIGHT",-8,-24)
		frame.tooltip:SetClampedToScreen(false);
		
		--frame.tooltip:Hide()
			
		frame.typeDropdown = self.AceGUI:Create("Dropdown")
		frame.typeDropdown:SetList({spell="Ability",item="Item",macro="Macro"},{'spell',"item","macro"})
		frame.typeDropdown:SetCallback("OnValueChanged", onActionTypeChange)
		frame.typeDropdown:SetWidth(80)
		
		frame.actionNameLabel = WhatsNext.AceGUI:Create('Label');
		frame.actionNameLabel:SetText("Spell Name:");
		frame.actionNameLabel:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
		frame.actionNameLabel:SetWidth(120)
		frame.actionNameLabel.label:SetJustifyH("RIGHT")

		frame.valueDropdown = self.AceGUI:Create("Dropdown")
		frame.valueDropdown:SetWidth(250)
		frame.valueDropdown:SetCallback("OnValueChanged",onActionChange)
		
		frame.icon = CreateFrame("Button","EntryIconButton",frame.frame)
		frame.icon:SetPoint("TOPRIGHT",frame.frame,"TOPRIGHT",-15,-31)
		frame.icon:SetWidth(45)
		frame.icon:SetHeight(45)
		--frame.icon:SetPoint("BOTTOMRIGHT",frame.frame,"BOTTOMRIGHT",-6,8)
		
		frame.icon:SetScript("OnMouseDown",function() 
			local type = frame.entry.type;
			local value = frame.entry[type];
			if type == "spell" then
				PickupSpell(value)
			elseif type == "item" then
				PickupItem(value)
			elseif type == "macro" then
				PickupMacro(value)
			end
		end)

		frame.icon:SetScript("OnEnter",function(btn) 
			GameTooltip_SetDefaultAnchor( GameTooltip, UIParent )
			GameTooltip:ClearAllPoints();
			
			GameTooltip:SetPoint("TOPRIGHT",btn,"TOPLEFT")
				
			if not GameTooltip.bg then
				GameTooltip.bg = GameTooltip:CreateTexture(nil,"BACKGROUND",nil,1)
				GameTooltip.bg:SetPoint("TOPLEFT",3,-3)
				GameTooltip.bg:SetPoint("BOTTOMRIGHT",-3,3)
				GameTooltip.bg:SetColorTexture(0,0,0,1)
			end
			GameTooltip.bg:Show()
			
			local type = frame.entry.type;
			local value = frame.entry[type];
			
			if type == "spell"then
				GameTooltip:SetSpellByID(tonumber(value))
				GameTooltip:Show()
			elseif type == "item" then
				GameTooltip:SetItemByID(tonumber(value))
				GameTooltip:Show()
			elseif type == "logicset" then
				GameTooltip:SetText("Logic Set")
				GameTooltip:AddDoubleLine("Name:",value,1,1,1)
				GameTooltip:Show()
			elseif type == "note" then
				GameTooltip:SetText("Note")
				GameTooltip:AddLine(value,1,1,1)
				GameTooltip:Show()
			elseif type == "macro" then
				GameTooltip:SetText("Macro")
				GameTooltip:AddLine(GetMacroBody(value),1,1,1)
				GameTooltip:Show()
			end
		end)
		frame.icon:SetScript("OnLeave",function(btn) 
			GameTooltip:Hide()
			if GameTooltip.bg then
				GameTooltip.bg:Hide()
			end
		end)
		
		
		
		
		frame.conditionsScrollContainer = self.AceGUI:Create("InlineGroup")
		frame.conditionsScrollContainer:SetFullWidth(true)
		frame.conditionsScrollContainer:SetHeight(200)
		frame.conditionsScrollContainer:SetLayout("Fill")

		
		frame.conditionsScrollFrame = self.AceGUI:Create("ScrollFrame")
		frame.conditionsScrollFrame:SetLayout("Flow")
		frame.addConditionButton = self.AceGUI:Create('Button');
		frame.addConditionButton:SetWidth(80);
		frame.addConditionButton:SetText('Add');
		frame.addConditionButton:SetCallback('OnClick', function()	
			WhatsNext:ShowConditionFrame(0,nil,function(condition,index)
				if index and index >0 then
					frame.entry.checks[index] = condition;
				else
					tinsert(frame.entry.checks,condition);
				end
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
				UpdateConditionsContainer()
			end,function()
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
			end)
		end);
		frame.editConditionButton = self.AceGUI:Create('Button');
		frame.editConditionButton:SetWidth(80);
		frame.editConditionButton:SetText('Edit');
		frame.editConditionButton:SetCallback('OnClick',  function()	
			local selected = WhatsNext.entryFrame.conditionsScrollFrame.selected;
			WhatsNext:ShowConditionFrame(selected,frame.entry.checks[selected],function(condition,index)
				if index and index >0 then
					frame.entry.checks[index] = condition;
				else
					tinsert(frame.entry.checks,condition);
				end
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
				UpdateConditionsContainer()
			end,function()
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
			end)
		end);
		
		frame.removeConditionButton = self.AceGUI:Create('Button');
		frame.removeConditionButton:SetWidth(80);
		frame.removeConditionButton:SetText('Remove');
		frame.removeConditionButton:SetCallback('OnClick', function()
			local selected = WhatsNext.entryFrame.conditionsScrollFrame.selected;
			tremove(frame.entry.checks,selected);
			UpdateConditionsContainer()
		end);
		
		frame.appearenceButton = self.AceGUI:Create('Button');
		frame.appearenceButton:SetWidth(160);
		--frame.appearenceButton:SetDisabled(true);
		frame.appearenceButton:SetText('Appearence / Sound');
		frame.appearenceButton:SetCallback('OnClick', function()
			WhatsNext:ShowAppearenceFrame(selected,frame.entry,function() 	
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
			end,function() 
				WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
			end)
		end);
		
		frame.okayButton = self.AceGUI:Create('Button');
		frame.okayButton:SetWidth(80);
		frame.okayButton:SetText('Okay');
		frame.okayButton:SetCallback('OnClick', function()
			confirmFunction(WhatsNext,frame.entry,frame.sourceIndex,frame.isNew)
		end);
		
		frame.cancelButton = self.AceGUI:Create('Button');
		frame.cancelButton:SetWidth(80);
		frame.cancelButton:SetText('Cancel');
		frame.cancelButton:SetCallback('OnClick', function() 
			cancelFunction();
		end);
		
		
		
		frame:AddChild(frame.typeLabel)
		frame:AddChild(createSpacer(5))
		frame:AddChild(frame.typeDropdown)
		frame:AddChild(frame.actionNameLabel)
		frame:AddChild(createSpacer(5))
		frame:AddChild(frame.valueDropdown)
		frame:AddChild(createSpacer(29))
		frame:AddChild(frame.conditionsScrollContainer)		
		frame:AddChild(frame.addConditionButton)
		frame:AddChild(frame.editConditionButton)
		frame:AddChild(frame.removeConditionButton)
		frame:AddChild(createSpacer(80))
		frame:AddChild(frame.appearenceButton)
		frame:AddChild(createSpacer(80))
		frame:AddChild(frame.okayButton)
		frame:AddChild(frame.cancelButton)
				
		frame:ResumeLayout()
		frame:DoLayout()
	end
	
	self.entryFrame:SetCallback("OnClose", cancelFunction)

	self.entryFrame.isNew = isNew
	self.entryFrame.conditionsScrollFrame.selected = 0;
	self.entryFrame.sourceIndex = sourceIndex
	self.entryFrame.entry = entry and DeepCopy(entry) or {type="spell",checks={}}
	self.entryFrame.typeDropdown:SetValue(self.entryFrame.entry.type)
	UpdateConditionsContainer();
	onActionTypeChange(self.entryFrame.typeDropdown,nil,self.entryFrame.entry.type)
	WhatsNext_ShowOptionsScreen(WhatsNext.entryFrame.frame)
end