local defaultIcon = "Interface\\Icons\\INV_Misc_QuestionMark";
local function GetItemId(itemName)
	local itemLink = select(2,GetItemInfo(itemName))
	if itemLink then
		return select(5,string.find(itemLink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+):?(%d*):?(%d*):?(%d*):?(%d*):?(%d*):?(%-?%d*):?(%-?%d*):?(%d*):?(%d*):?(%-?%d*)|?h?%[?([^%[%]]*)%]?|?h?|?r?"))
	end
end

local function getGroupChatChannel()
	if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
		return "INSTANCE_CHAT";
	elseif UnitInRaid("player") then
		return "RAID";
	elseif IsInGroup() then
		return "PARTY";
	else
		return "SAY";
	end
end

function WhatsNext:EntryToString(entry)
	local blockType = entry.type or "spell"
	local exportString = "{"
	exportString = exportString .. "\n\ttype=\"".. blockType .. "\","
	exportString = exportString .. "\n\t" .. blockType .. "=\"".. (blockType == "spell" and WhatsNext:GetSpellID(entry[blockType]) or entry[blockType] or "") .. "\","
	if entry.unit then
		exportString = exportString .. "\n\tunit=\"".. entry.unit .. "\","
	end
	if entry.copyUnits then
		exportString = exportString .. "\n\tcopyUnits={\n\t\t"
		for k,v in ipairs(entry.copyUnits) do
			exportString = exportString .. "\"" .. v .. "\","
		end
		exportString = exportString .. "\n\t},"
	end
	exportString = exportString .. "\n\tchecks={"
	for i, check in pairs(entry.checks) do
		exportString = exportString .. "\n\t\t{[\"type\"]=\"" .. tostring(check["type"]) .. "\","
		for var,val in pairs(check) do
			if var ~= "type" then
				exportString = exportString .. "[\"" .. tostring(var) .. "\"]="
				if type(val) == "boolean" or type(val) == "number" then
					exportString = exportString .. tostring(val) .. ","
				else
					exportString = exportString .. "\"" .. tostring(val) .. "\","
				end
			end
		end
		exportString = exportString .. "},"
	end
	return exportString .. "\n\t}\n}"
end

local function updateSelectedBlock(index)
	local frame = WhatsNext.rotationManagerFrame
	if frame.entryBlocks then
		for i,entryBlock in ipairs(frame.entryBlocks) do
			
			if i == frame.selectedIndex then
				entryBlock.frame.texture:SetColorTexture(.2,.2,.2,1)
			elseif i%2==1 then
				entryBlock.frame.texture:SetColorTexture(.05,.05,.05,1)
			else
				entryBlock.frame.texture:SetColorTexture(.1,.1,.1,1)
			end
		end
	end
	
	
	local noSelection = not frame.selectedIndex or (frame.selectedIndex == 0)
	frame.copyEntryButton:SetDisabled(noSelection);
	frame.editEntryButton:SetDisabled(noSelection);
	frame.removeEntryButton:SetDisabled(noSelection);
	
	local entryText = noSelection and "All" or ("#".. frame.selectedIndex)
	frame.exportEntryButton:SetText('Export ' .. entryText);
	frame.shareGuildButton:SetText('Share ' .. entryText .. ' With Guild');
	frame.shareGroupButton:SetText('Share ' .. entryText .. ' With Group');
	frame.shareTargetButton:SetText('Share ' .. entryText .. ' With Target');
end

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 shareEntry(index, channel, target)
	local entry = WhatsNext.workRotation[index]
	local id = entry[entry.type];
	if entry.type == "spell" then
		local spell = WhatsNext:GetSpell(tonumber(id) or id) 
		local spellName = spell and spell.link or GetSpellInfo(id) or id;
		ChatThrottleLib:SendChatMessage("BULK","WN","#" .. index .. " Cast Ability: "..spellName,channel, nil, target)
	elseif entry.type == "item" then
		local itemName, itemLink = GetItemInfo(id)
		ChatThrottleLib:SendChatMessage("BULK","WN",("#" .. index .. " Use Item: "..(itemLink or itemName or "")),channel, nil, target)
	elseif entry.type == "macro" then
		ChatThrottleLib:SendChatMessage("BULK","WN",("#" .. index .. " Run Macro: "..(select(1,GetMacroInfo(id)) or "")),channel, nil, target)
	elseif entry.type == "note" then
		ChatThrottleLib:SendChatMessage("BULK","WN","#" .. index .. " "..id,channel, nil, target)
	end
	
	

	local checkCount = #(entry.checks)
	if checkCount > 0 then
		for i = 1, checkCount do
			ChatThrottleLib:SendChatMessage("BULK","WN","    "..WhatsNext:GetCleanCheckText(entry.checks[i]),channel, nil, target)
		end
	end
end

local function shareEntries(channel, target)

	local playerClass = UnitClass("player");
	local currentSpec = GetSpecialization()
	local currentSpecName = currentSpec and select(2, GetSpecializationInfo(currentSpec)) or "None"

	local selectedIndex = WhatsNext.rotationManagerFrame.selectedIndex
	if selectedIndex and selectedIndex > 0 then
		ChatThrottleLib:SendChatMessage("BULK","WN","What Next? - Rotation for "..currentSpecName.." " .. playerClass,channel, nil, target)
		shareEntry(selectedIndex, channel, target)
	else
		ChatThrottleLib:SendChatMessage("BULK","WN","What Next? - Rotation Entry for "..currentSpecName.." " .. playerClass,channel, nil, target)
		for i,entry in ipairs(WhatsNext.workRotation) do
			shareEntry(i, channel, target)
		end
	end
end

local function populateRotationTable()
	local frame = WhatsNext.rotationManagerFrame
	
	if frame.entryBlocks then
		for i,entryBlock in ipairs(frame.entryBlocks) do
			entryBlock.frame:Hide()
			for key,val in pairs(entryBlock.frame) do
				if type(val) =="table" and val.Hide then
					val:Hide()
				end
			end
		end
	end
	frame.scrollFrame:ReleaseChildren()
	frame.entryBlocks = {}
	
	
	for i,entry in ipairs(WhatsNext.workRotation) do
		local entryBlock = WhatsNext.AceGUI:Create("SimpleGroup")
		entryBlock.index = i
		entryBlock.frame:SetMovable(true)
		entryBlock:SetFullWidth(true)
		entryBlock:SetLayout("Flow")
		frame.entryBlocks[i] = entryBlock
		
		local spacer = WhatsNext.AceGUI:Create('Label');
		spacer:SetText(" ");
		spacer:SetFont("Fonts\\FRIZQT__.TTF", 28, "OUTLINE, MONOCHROME")
		spacer:SetWidth(400)
		entryBlock:AddChild(spacer)
		entryBlock.checkLabel = WhatsNext.AceGUI:Create('Label');
		entryBlock.checkLabel:SetText(" ");
		entryBlock.checkLabel:SetFont("Fonts\\FRIZQT__.TTF", 12.5, "")
		entryBlock.checkLabel:SetWidth(680)
		entryBlock.checkLabel.label:SetJustifyH("RIGHT")

		
		frame.scrollFrame:AddChild(entryBlock)
		
		if entryBlock.frame.icon then
			entryBlock.frame.icon:Show()
		else
			entryBlock.frame.icon = entryBlock.frame:CreateTexture()
		end
		entryBlock.frame.icon:SetPoint("TOPLEFT",entryBlock.frame,"TOPLEFT",2,-2)
		entryBlock.frame.icon:SetWidth(30)
		entryBlock.frame.icon:SetHeight(30)
	
	
		if entryBlock.frame.entryTitle then
			entryBlock.frame.entryTitle:Show()
		else
			entryBlock.frame.entryTitle = entryBlock.frame:CreateFontString(nil,"ARTWORK")
		end
		entryBlock.frame.entryTitle:SetFont("Fonts\\FRIZQT__.TTF", 16, "")
		entryBlock.frame.entryTitle:SetPoint("TOPLEFT",entryBlock.frame.icon,"TOPRIGHT",5,0)
		entryBlock.frame.entryTitle:SetPoint("BOTTOMLEFT",entryBlock.frame.icon,"BOTTOMRIGHT",5,0)
		entryBlock.frame.entryTitle:SetTextColor(1,0.8196079,0,1)
		entryBlock.frame.entryTitle:SetJustifyH("LEFT")
		entryBlock.frame.entryTitle:SetJustifyV("CENTER")
		entryBlock.frame.entryTitle:SetWidth(500)
		
		entryBlock.frame.entryIndex = entryBlock.frame:CreateFontString(nil,"ARTWORK")
		entryBlock.frame.entryIndex:SetFont("Fonts\\ARIALN.TTF", 16, "")
		entryBlock.frame.entryIndex:SetPoint("TOPRIGHT",entryBlock.frame,"TOPRIGHT",-4,-4)
		entryBlock.frame.entryIndex:SetTextColor(1,0.8196079,0,1)
		entryBlock.frame.entryIndex:SetJustifyH("RIGHT")
		entryBlock.frame.entryIndex:SetJustifyV("CENTER")
		entryBlock.frame.entryIndex:SetWidth(40)
		
		entryBlock.frame.texture = entryBlock.frame:CreateTexture(nil, "BACKGROUND")
		entryBlock.frame.texture:SetColorTexture(.5,.5,.5,0)
		entryBlock.frame.texture:SetPoint("TOPLEFT",entryBlock.frame,"TOPLEFT",-4,0)
		entryBlock.frame.texture:SetPoint("BOTTOMRIGHT",entryBlock.frame,4,-3)
		
		entryBlock.frame.button = CreateFrame("Button","blockButton"..i,entryBlock.frame)
		entryBlock.frame.button:EnableMouse(true)
		entryBlock.frame.button:RegisterForDrag("LeftButton")
		entryBlock.frame.button.index = i
		entryBlock.frame.button:SetPoint("TOPLEFT",entryBlock.frame,-4,0)
		entryBlock.frame.button:SetPoint("BOTTOMRIGHT",entryBlock.frame,4,-3)
		entryBlock.frame.button:SetScript("OnClick",function(btn) 
			if frame.dragging then
				local entry = WhatsNext.workRotation[frame.dragging];
				tremove(WhatsNext.workRotation,frame.dragging)
				tinsert(WhatsNext.workRotation,btn.index,entry)
				frame.dragging = nil
				
				frame.entryBlocks[i].frame:SetFrameStrata("FULLSCREEN_DIALOG")
				frame.entryBlocks[i].frame:ClearAllPoints()
				populateRotationTable()
			else
				frame.selectedIndex = (frame.selectedIndex~= btn.index) and btn.index or 0
				updateSelectedBlock()
			end
		end)
		entryBlock.frame.button:SetScript("OnDoubleClick",function(btn) 

			local entry = WhatsNext.workRotation[btn.index]
			WhatsNext:ShowEntryFrame(false,btn.index,entry,WhatsNext.SetWorkEntry,function() 
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end)
		entryBlock.frame.button:SetScript("OnDragStart",function(btn) 
			frame.dragging = btn.index
			local uiScale, x, y = UIParent:GetEffectiveScale(), GetCursorPosition()
			--entryBlock.frame:StartMoving()
			entryBlock.frame:ClearAllPoints()
			entryBlock.frame:SetPoint("LEFT", nil, "BOTTOMLEFT", x / uiScale+10, y / uiScale)
			entryBlock.frame:SetFrameStrata("TOOLTIP")
			--btn:Hide()
		end)
		entryBlock.frame:SetScript("OnUpdate",function(entryFrame) 
			if frame.dragging == entryFrame.button.index then
				local uiScale, x, y = UIParent:GetEffectiveScale(), GetCursorPosition()
				entryFrame:ClearAllPoints()
				entryFrame:SetPoint("LEFT", nil, "BOTTOMLEFT", x / uiScale+10, y / uiScale)
			end
		end)
		entryBlock.frame.button:SetScript("OnEnter",function(btn) 
			frame.mouseOver = btn.index
			
			GameTooltip_SetDefaultAnchor( GameTooltip, UIParent )
			GameTooltip:ClearAllPoints();
			
				
			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()
		end)
		entryBlock.frame.button:SetScript("OnLeave",function(btn) 
			frame.mouseOver = 0
			GameTooltip:Hide()
			if GameTooltip.bg then
				GameTooltip.bg:Hide()
			end
		end)
		entryBlock.frame.button:SetScript("OnUpdate",function(btn) 
			if frame.mouseOver == btn.index then
				local entry = WhatsNext.workRotation[btn.index]
				local scale = GameTooltip:GetEffectiveScale();
				local x, y = GetCursorPosition();
				GameTooltip:ClearAllPoints();
				GameTooltip:SetPoint("TOPLEFT", btn, "TOPRIGHT");
				if entry.type == "spell" and tonumber(entry.spell) then
					GameTooltip:SetSpellByID(tonumber(entry.spell))
					GameTooltip:Show()
				elseif entry.type == "item" then
					GameTooltip:SetItemByID(tonumber(entry.item) or GetItemId(entry.item))
					GameTooltip:Show()
				elseif entry.type == "logicset" then
					GameTooltip:SetText("Logic Set")
					GameTooltip:AddDoubleLine("Name:",entry.logicset,1,1,1)
					GameTooltip:Show()
				elseif entry.type == "note" then
					GameTooltip:SetText("Note")
					GameTooltip:AddLine(entry.note,1,1,1)
					GameTooltip:Show()
				elseif entry.type == "macro" then
					GameTooltip:SetText("Macro")
					GameTooltip:AddLine(GetMacroBody(entry.macro),1,1,1)
					GameTooltip:Show()
				end
			end
		end)
		
		local topLine = ""
		local iconPath = "Interface\\Icons\\INV_Misc_QuestionMark"
		local id = entry[entry.type];
		if entry.type == "spell" then
			iconPath = select(3,GetSpellInfo(id)) or defaultIcon
			local spell = WhatsNext:GetSpell(tonumber(id) or id) 
			topLine = spell and spell.name or GetSpellInfo(id) or id;
		elseif entry.type == "item" then
			iconPath = select(10,GetItemInfo(id)) or defaultIcon
			topLine = (select(1,GetItemInfo(id)) or "");
		elseif entry.type == "macro" then
			iconPath = select(2,GetMacroInfo(id)) or defaultIcon
			topLine = (select(1,GetMacroInfo(id)) or "");
		elseif entry.type == "note" then
			iconPath = "Interface\\Icons\\INV_MISC_NOTE_05"
			topLine = (id);
		elseif entry.type == "logicset" then
			iconPath = "Interface\\Icons\\MISC_ARROWRIGHT"
			topLine = (id);
		end
		
		local checkText = ""
		local checkCount = #(entry.checks)
		if checkCount > 0 then
			checkText = WhatsNext:GetCheckText(entry.checks[1])
			for i = 2, checkCount do
				checkText = checkText .. "\n"..WhatsNext:GetCheckText(entry.checks[i])
			end
		end
		entryBlock.checkLabel:SetText(checkText)
		entryBlock.frame.icon:SetTexture(iconPath)
		entryBlock.frame.entryTitle:SetText(topLine)
		entryBlock.frame.entryIndex:SetText(tostring(i))
		
		entryBlock:AddChild(createSpacer(5))
		entryBlock:AddChild(entryBlock.checkLabel)
		entryBlock:AddChild(createSpacer(600))
		entryBlock.frame:Show()
	end
	if frame.selectedIndex and #WhatsNext.workRotation < frame.selectedIndex then
		frame.selectedIndex = #WhatsNext.workRotation
	end
	
	updateSelectedBlock()
	frame.scrollFrame:DoLayout()
	frame:DoLayout()	

	for i=#WhatsNext.workRotation +1, #WhatsNext.rotationManagerFrame.entryBlocks do
		WhatsNext.rotationManagerFrame.entryBlocks[i].frame:Hide()
	end
end

local function populateRotationDropdown()
	WhatsNext.rotationManagerFrame.rotationDropdown:SetList({});
	
	local logicSets = WhatsNext.db.profile.castSequences[WhatsNext.rotationManagerFrame.class][WhatsNext.rotationManagerFrame.spec]
	WhatsNext.rotationManagerFrame.selectedRotationIndex = 1;
	for i,logicSet in ipairs(logicSets) do
		WhatsNext.rotationManagerFrame.rotationDropdown:AddItem(i,logicSet.name);
		if logicSet.use then
			WhatsNext.rotationManagerFrame.selectedRotationIndex = i
		end
	end

	WhatsNext.rotationManagerFrame.rotationDropdown:SetValue(WhatsNext.rotationManagerFrame.selectedRotationIndex);
	populateRotationTable()
end

local function populateSpecDropdown()
	WhatsNext.rotationManagerFrame.specDropdown:SetList({});
	for i=1, WhatsNext.CLASS_SPECIALIZATION_COUNTS[WhatsNext.rotationManagerFrame.class] or 3 do
		WhatsNext.rotationManagerFrame.specDropdown:AddItem(i,WhatsNextLocal:Localize(WhatsNext.rotationManagerFrame.class..i));
	end
	WhatsNext.rotationManagerFrame.spec = WhatsNext.rotationManagerFrame.class == WhatsNext.rotationManagerFrame.playerClass and GetSpecialization() or 1
	WhatsNext.rotationManagerFrame.specDropdown:SetValue(WhatsNext.rotationManagerFrame.spec);
	populateRotationDropdown()
end

local function createSpacer(width)
	local label = WhatsNext.AceGUI:Create('Label');
	label:SetText(" ");
	label:SetWidth(width)
	return label
end

function WhatsNext:SetWorkEntry(entry,index,isNew)
	if not isNew then
		WhatsNext.workRotation[index] = entry;
	else
		tinsert(WhatsNext.workRotation,index, entry);
	end
	WhatsNext.rotationManagerFrame.selectedIndex = index
	populateRotationTable()
	WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
end

function WhatsNext:SetWorkRotation(index)
	self.class = select(2,UnitClass("player"));
	self.spec =  GetSpecialization() or 1
	self.rotationIndex = index
	self.rotationChanged = false
	
	if index == -1 then
		self.newWorkRotation = true;
		self.workRotation = {
			name = "Unnamed",
			lastModified = time(),
			use = nil,
		}
	elseif index == 0 then
		for i, rotation in ipairs(self.db.profile.castSequences[self.class][self.spec]) do
			if rotation.use then
				self.rotationIndex = i;
			end
		end
	
		self.newWorkRotation = false;
		
		if not self.db.profile.castSequences[self.class][self.spec][self.rotationIndex] then
			self:SetWorkRotation(-1);
			self.workRotation.name = "Default"
			return;
		end
		
		self.workRotation = DeepCopy(self.db.profile.castSequences[self.class][self.spec][self.rotationIndex])
	else
		self.newWorkRotation = false;
		if not self.db.profile.castSequences[self.class][self.spec][self.rotationIndex] then
			self:SetWorkRotation(-1);
			self.workRotation.name = "Default"
			return;
		end
		self.workRotation = DeepCopy(self.db.profile.castSequences[self.class][self.spec][self.rotationIndex])
	end
	populateRotationTable()
	self.rotationManagerFrame.rotationNameField:SetText(self.workRotation.name or "")
end


function WhatsNext:IsRotationManagerFrameVisible()
	return self.rotationManagerFrame and self.rotationManagerFrame:IsVisible()
end

function WhatsNext:HideRotationManagerFrame()
	if WhatsNext:IsRotationManagerFrameVisible() then
		self.rotationManagerFrame.frame:Hide()
	end
end

function WhatsNext:ShowRotationManagerFrame()
	if not self.rotationManagerFrame then
		local frame = self.AceGUI:Create("Window")
		_G["WhatsNext_RotationManagerFrame"] = frame
		
		tinsert(UISpecialFrames, "WhatsNext_RotationManagerFrame") 
		self.rotationManagerFrame = frame
		WhatsNext_AddOptionsScreen(WhatsNext.rotationManagerFrame.frame)
		
		frame.class = select(2,UnitClass("player"));
		frame.spec =  GetSpecialization() or 1
		
		frame:SetWidth(750)
		frame:SetHeight(715)
		frame:SetTitle("What's Next? - Rotation Management")
		frame:SetStatusText("")
		frame:EnableResize(false);
		frame:SetCallback("OnClose", function(widget) 
			WhatsNext:ApplyMainSettings()
			WhatsNext:UpdateActiveLogicSet()
		end)
		frame:SetLayout("Flow")
		frame:SetAutoAdjustHeight(false)
		
	
		frame:AddChild(createSpacer(200))
		
		frame.rotationNameField = WhatsNext.AceGUI:Create('EditBox');
		frame.rotationNameField.editbox:SetTextColor(1,0.8196079,0,1)
		frame.rotationNameField.editbox:SetScript("OnEnterPressed", function()
			frame.rotationNameField.editbox:ClearFocus()
		end)
		frame.rotationNameField.editbox:SetScript("OnEscapePressed", function()
			frame.rotationNameField.editbox:ClearFocus()
		end)
		frame.rotationNameField:SetWidth(300)
		frame.rotationNameField.editbox:SetScale(2)
		frame.rotationNameField.editbox:SetJustifyH("CENTER")
		frame.rotationNameField:DisableButton(true)

		frame:AddChild(frame.rotationNameField)
	
		frame:AddChild(createSpacer(70))
		frame.changeRotationButton = self.AceGUI:Create('Button');
		frame.changeRotationButton:SetWidth(150);
		frame.changeRotationButton:SetText('Pick Active Rotation');
		frame.changeRotationButton:SetCallback('OnClick', function()
			WhatsNext:ShowRotationPickerFrame(function() 
				WhatsNext:SetWorkRotation(0)
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end);
		frame:AddChild(frame.changeRotationButton)
		
		
		frame.scrollContainer = self.AceGUI:Create("InlineGroup") -- "InlineGroup" is also good
		frame.scrollContainer:SetFullWidth(true)
		frame.scrollContainer:SetHeight(565)
		
		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,-10)
		frame.frame.texture:SetPoint("BOTTOMRIGHT",frame.frame,"BOTTOMRIGHT",-6,8)
		frame.scrollContainer:SetLayout("Fill") -- important!

		frame:AddChild(frame.scrollContainer)

		frame.scrollFrame = self.AceGUI:Create("ScrollFrame")
		frame.scrollFrame:SetLayout("Flow") -- probably?
		frame.scrollContainer:AddChild(frame.scrollFrame)
				
		
		
		frame.copyEntryButton = self.AceGUI:Create('Button');
		frame.copyEntryButton:SetWidth(80);
		frame.copyEntryButton:SetText('Copy');
		frame.copyEntryButton:SetCallback('OnClick', function()	
			local index = WhatsNext.rotationManagerFrame.selectedIndex;
			local entry = WhatsNext.workRotation[index]
			WhatsNext:ShowEntryFrame(true,index,entry,WhatsNext.SetWorkEntry,function()
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end);
		frame.addEntryButton = self.AceGUI:Create('Button');
		frame.addEntryButton:SetWidth(80);
		frame.addEntryButton:SetText('Add');
		frame.addEntryButton:SetCallback('OnClick', function()	
			WhatsNext:ShowEntryFrame(true,1,nil,WhatsNext.SetWorkEntry,function() 
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end);
		frame.editEntryButton = self.AceGUI:Create('Button');
		frame.editEntryButton:SetWidth(80);
		frame.editEntryButton:SetText('Edit');
		frame.editEntryButton:SetCallback('OnClick', function()	
			local index = WhatsNext.rotationManagerFrame.selectedIndex;
			local entry = WhatsNext.workRotation[index]
			WhatsNext:ShowEntryFrame(false,index,entry,WhatsNext.SetWorkEntry,function() 
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end);
		frame.removeEntryButton = self.AceGUI:Create('Button');
		frame.removeEntryButton:SetWidth(80);
		frame.removeEntryButton:SetText('Remove');
		frame.removeEntryButton:SetCallback('OnClick', function()
			local index = WhatsNext.rotationManagerFrame.selectedIndex;
			if index and index > 0 then
				tremove(WhatsNext.workRotation, index)
			end
			populateRotationTable()
		end);
		
		frame.importEntryButton = self.AceGUI:Create('Button');
		frame.importEntryButton:SetWidth(80);
		frame.importEntryButton:SetText('Import');
		frame.importEntryButton:SetCallback('OnClick', function()	
			WhatsNext:ShowImportFrame(function(importText)
				local importBody
				if importText and importText ~= "" and type(importText) == "string" then
						local func, errors = loadstring("return "..importText)
						if not func then
							return false, errors
						end
						importBody = func()
				
					for i,entry in ipairs(importBody) do
						if not entry["type"] or not entry[entry["type"]] then
							return false, "Unrecognisable rotation entry (#"..i..")."
						end
					end
				
					local startIndex = WhatsNext.rotationManagerFrame.selectedIndex and (WhatsNext.rotationManagerFrame.selectedIndex > 0) and WhatsNext.rotationManagerFrame.selectedIndex or #WhatsNext.workRotation

					for i,entry in ipairs(importBody) do
						WhatsNext:SetWorkEntry(entry,startIndex + i,true)
					end
				
				end
			
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
				return true
			end,function()
				WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
			end)
		end);
		
		frame.exportEntryButton = self.AceGUI:Create('Button');
		frame.exportEntryButton:SetWidth(100);
		frame.exportEntryButton:SetText('Export');
		frame.exportEntryButton:SetCallback('OnClick', function()
			local index = WhatsNext.rotationManagerFrame.selectedIndex;
			local count
			local exportString = "{"
			
			if index and index > 0 then
				exportString = exportString .. WhatsNext:EntryToString(WhatsNext.workRotation[index]) .. ","
				count = 1
			else
				for i, entry in ipairs(WhatsNext.workRotation) do
					exportString = exportString .. WhatsNext:EntryToString(entry) .. ","
				end
				count = #WhatsNext.workRotation
			end
			exportString = exportString .. "}"
		
			WhatsNext:ShowExportFrame(exportString,count, function() 
				WhatsNext:ShowRotationManagerFrame()
			end)
			WhatsNext.rotationManagerFrame.frame:Hide()
		end);
		
		frame.shareGuildButton = self.AceGUI:Create('Button');
		frame.shareGuildButton:SetWidth(178);
		frame.shareGuildButton:SetText('Share With Guild');
		frame.shareGuildButton:SetCallback('OnClick', function()
			shareEntries("GUILD");
		end);
		
		frame.shareGroupButton = self.AceGUI:Create('Button');
		frame.shareGroupButton:SetWidth(178);
		frame.shareGroupButton:SetText('Share With Group');
		frame.shareGroupButton:SetCallback('OnClick', function()
			shareEntries(getGroupChatChannel());
		end);
		frame.shareTargetButton = self.AceGUI:Create('Button');
		frame.shareTargetButton:SetWidth(178);
		frame.shareTargetButton:SetText('Share With Target');
		frame.shareTargetButton:SetCallback('OnClick', function()
			if GetUnitName("target", true) then
				shareEntries("WHISPER",GetUnitName("target", true));
			end
		end);
		
		frame.saveButton = self.AceGUI:Create('Button');
		frame.saveButton:SetWidth(80);
		frame.saveButton:SetText('Save');
		frame.saveButton:SetCallback('OnClick', function()	
			for i, rotation in ipairs(WhatsNext.db.profile.castSequences[WhatsNext.class][WhatsNext.spec]) do
				rotation.use = nil;
			end
			
			WhatsNext.workRotation.lastModified = time()
			WhatsNext.workRotation.use = "General"
			WhatsNext.workRotation.name = frame.rotationNameField:GetText()
			
			if WhatsNext.newWorkRotation then
				tinsert(WhatsNext.db.profile.castSequences[WhatsNext.class][WhatsNext.spec], WhatsNext.workRotation);
			else
				WhatsNext.db.profile.castSequences[WhatsNext.class][WhatsNext.spec][WhatsNext.rotationIndex] = WhatsNext.workRotation			
			end
			
			WhatsNext.rotationManagerFrame.frame:Hide()
		end);
	
		frame.cancelButton = self.AceGUI:Create('Button');
		frame.cancelButton:SetWidth(80);
		frame.cancelButton:SetText('Cancel');
		frame.cancelButton:SetCallback('OnClick', function()
			WhatsNext.rotationManagerFrame.frame:Hide()
		end);
		
		--frame:AddChild(createSpacer(0))
		
		frame:AddChild(frame.addEntryButton)
		frame:AddChild(frame.copyEntryButton)
		frame:AddChild(frame.editEntryButton)
		frame:AddChild(frame.removeEntryButton)
		frame:AddChild(createSpacer(33))
		frame:AddChild(frame.importEntryButton)
		frame:AddChild(frame.exportEntryButton)
		
		frame:AddChild(createSpacer(180))
		
		frame:AddChild(frame.shareGuildButton)
		frame:AddChild(frame.shareGroupButton)
		frame:AddChild(frame.shareTargetButton)
		
		
		frame:AddChild(createSpacer(32))
		frame:AddChild(frame.saveButton)
		frame:AddChild(frame.cancelButton)
	end

	WhatsNext_ShowOptionsScreen(WhatsNext.rotationManagerFrame.frame)
	self:SetWorkRotation(self.rotationIndex and self.rotationIndex > 0 and self.rotationIndex or 0)
	WhatsNext.rotationManagerFrame:DoLayout()
end