local arguementElements = {}

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


local function GetConditionBlock()
	local condition = {}
	condition.type = WhatsNext.conditionFrame.checkDropdown:GetValue()
	condition.invert = WhatsNext.conditionFrame.invertCheckbox:GetValue() == true
	--print("type = " .. condition.type)
	--print("invert = " ..tostring( condition.invert))
	
	local argsFrames = WhatsNext.conditionFrame.arguementsGroups;
	for name, argFrame in pairs(argsFrames.lines) do
		if argFrame.type == "percent" or argFrame.type == "integer" then
			condition[name] = argFrame.slider:GetValue()
		elseif argFrame.type == "text" then
			condition[name] = argFrame.text:GetText()
		elseif argFrame.type == "spell" then
			condition[name] = WhatsNext:GetSpellID(argFrame.text:GetText()) or argFrame.text:GetText()
		elseif argFrame.type == "dropdown" then
			if argFrame.dd2 then
				condition[name] = argFrame.dd2:GetValue()
			else
				condition[name] = argFrame.dd1:GetValue()
			end
		end
		
		--print(name.." = " .. condition[name])
	end
	
	
	return condition
end

local function onCheckChange(btn,event,value)
	local frame = WhatsNext.conditionFrame;
	local argFrame = WhatsNext.conditionFrame.arguementsGroups;
	
	argFrame:ReleaseChildren()
	argFrame:DoLayout()
	argFrame.lines = {}
	local arguements = WhatsNext:GetArguments(value)
	if arguements then
		for name,arguement in pairs(arguements) do
			local value = frame.condition[name] or arguement.default
			--print(name,arguement.type,value)
			local arguementGroup = WhatsNext.AceGUI:Create("SimpleGroup")
			arguementGroup:SetFullWidth(true)
			arguementGroup:SetLayout("Flow")
			arguementGroup.type = arguement.type
			argFrame.lines[name] = arguementGroup
			argFrame:AddChild(arguementGroup)
			
			local label = WhatsNext.AceGUI:Create('Label');
			label:SetText((arguement.label or name) .. ":");
			label:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
			label:SetWidth(120)
			label.label:SetJustifyH("RIGHT")
			arguementGroup:AddChild(label)
			arguementGroup:AddChild(createSpacer(5))
			
			
			if arguement.type == "percent" then
				local slider = WhatsNext.AceGUI:Create('Slider');
				slider:SetWidth(300)
				slider:SetIsPercent(true)
				slider:SetSliderValues(arguement.min or 0,arguement.max or 1,arguement.increment or .01)
				slider:SetValue(value)
				slider:SetLabel("")
				arguementGroup.slider = slider
				arguementGroup:AddChild(slider)
			elseif arguement.type == "integer" then
				local slider = WhatsNext.AceGUI:Create('Slider');
				slider:SetWidth(300)
				slider:SetIsPercent(false)
				slider:SetSliderValues(arguement.min or 0,arguement.max or 10000000,arguement.increment or 1)
				slider:SetValue(value)
				slider:SetLabel("")
				arguementGroup.slider = slider
				arguementGroup:AddChild(slider)
			elseif arguement.type == "text" then
				local text = WhatsNext.AceGUI:Create('EditBox');
				text:SetWidth(300)
				text:DisableButton(true)
				text:SetText(value)
				text:SetLabel("")
				arguementGroup:AddChild(text)
				arguementGroup.text = text
			elseif arguement.type == "spell" then
				local text = WhatsNext.AceGUI:Create('EditBox');
				text:SetWidth(300)
				text:DisableButton(true)
				text:SetLabel("")
				text:SetText(WhatsNext:GetSpellName(value))
				arguementGroup.text = text
				
				label = WhatsNext.AceGUI:Create('Label');
				label:SetText("ID or Name. (|cFFFF0000Case Sensitive|r)");
				label:SetFont("Fonts\\FRIZQT__.TTF", 11, "")
				label:SetWidth(250)
				label.label:SetJustifyH("LEFT")
				
				arguementGroup:AddChild(text)
				arguementGroup:AddChild(createSpacer(5))
				arguementGroup:AddChild(label)
			elseif arguement.type == "dropdown" then
				local depth = 1
				local firstValue 
				local secondValue 
				local depth1List = {}
				for key,val in pairs(arguement.possibleValues) do
					if not firstValue then
						firstValue = key
					end
					if type(val) == "table" then
						depth = 2
						depth1List[key] = key
						for key2,val2 in pairs(val) do
							if not secondValue then
								secondValue = val2
							end
							if key2 == value then
								firstValue = key
								secondValue = val2
							end
						end
					end
				end
				
				--print(firstValue,secondValue)
				local dd1 = WhatsNext.AceGUI:Create("Dropdown")
				dd1:SetWidth(150)
				dd1.depth = 1
				dd1:SetLabel("")
				dd1.arguement = name
				dd1.possibleValues = arguement.possibleValues
				arguementGroup.dd1 = dd1
				arguementGroup:AddChild(dd1)
				
				if depth == 2 then
				
					dd1:SetList(depth1List)
					dd1:SetValue(firstValue)
				
					local dd2 = WhatsNext.AceGUI:Create("Dropdown")
					dd2:SetWidth(250)
					dd2.depth = 2
					dd2:SetLabel("")
					dd2.arguement = name
					dd2.dd1 = dd1
					dd2:SetList(arguement.possibleValues[firstValue])
					dd2:SetValue(secondValue)
					arguementGroup.dd2 = dd2
					arguementGroup:AddChild(dd2)
					
					dd1.dd2 = dd2
					dd1:SetCallback("OnValueChanged", function(dd,event,value) 
						dd.dd2:SetList(dd.possibleValues[value])
					
						for key2,val2 in pairs(dd.possibleValues[value]) do
							dd.dd2:SetValue(key2)
							do break end
						end
					end)
				else
					dd1:SetList(arguement.possibleValues)
				end
				
			end
		end
		
		argFrame:AddChild(createSpacer())
	end
	
	
	local label = WhatsNext.AceGUI:Create('Label');
	label:SetText("Invert:");
	label:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
	label:SetWidth(120)
	label.label:SetJustifyH("RIGHT")
	
	frame.invertCheckbox  = WhatsNext.AceGUI:Create('CheckBox');
	frame.invertCheckbox:SetValue(frame.condition.invert)
	frame.invertCheckbox:SetType("checkbox")
	frame.invertCheckbox:SetLabel("")
	
	frame.okayButton = WhatsNext.AceGUI:Create('Button');
	frame.okayButton:SetWidth(80);
	frame.okayButton:SetText('Okay');
	frame.okayButton:SetCallback('OnClick', function()
		frame.confirmFunction(GetConditionBlock(),frame.sourceIndex)
	end);
	
	frame.cancelButton = WhatsNext.AceGUI:Create('Button');
	frame.cancelButton:SetWidth(80);
	frame.cancelButton:SetText('Cancel');
	frame.cancelButton:SetCallback('OnClick', function() 
		frame.cancelFunction();
	end);
	
	argFrame:AddChild(label)
	argFrame:AddChild(createSpacer(5))
	argFrame:AddChild(frame.invertCheckbox)
	argFrame:AddChild(createSpacer(220))
	argFrame:AddChild(frame.okayButton)
	argFrame:AddChild(frame.cancelButton)
	frame:DoLayout()
	
	frame:SetHeight(90+argFrame.frame:GetHeight())
end

local function onCategoryChange(btn,event,value)
	WhatsNext.conditionFrame.category = value;
	local sampleChecks = WhatsNext:GetSampleCheckTexts(value)
	local sampleCheckList = {}
	local value
	for type,text in pairs(sampleChecks) do
		tinsert(sampleCheckList,type)
	end
	
	if #sampleCheckList == 0 then
		WhatsNext.conditionFrame.checkDropdown:SetList({"No checks of this type are available."})
		value = 1
	else
		table.sort(sampleCheckList, function(ca,cb) 
			return sampleChecks[ca] < sampleChecks[cb]
		end)
		WhatsNext.conditionFrame.checkDropdown:SetList(sampleChecks,sampleCheckList)
		local type = WhatsNext.conditionFrame.condition.type;
		value = sampleChecks[type] and type or sampleCheckList[1];
	end
	WhatsNext.conditionFrame.checkDropdown:SetValue(value)
	onCheckChange(WhatsNext.conditionFrame.checkDropdown,event,value)
end

function WhatsNext:ShowConditionFrame(sourceIndex, condition,confirmFunction,cancelFunction)
	if not self.conditionFrame then
		local frame = self.AceGUI:Create("Window")
		_G["WhatsNext_ConditionFrame"] = frame
		
		self.conditionFrame = frame
		WhatsNext_AddOptionsScreen(WhatsNext.conditionFrame.frame)
		tinsert(UISpecialFrames, "WhatsNext_ConditionFrame") 
		frame:SetWidth(750)
		frame:SetTitle("What's Next? - Condition Editor")
		frame:SetStatusText("")
		frame:EnableResize(false);
		frame:SetLayout("Flow")
		frame:SetCallback("OnClose", cancelFunction)
		frame:SetAutoAdjustHeight(false)
		
		frame.tooltip = CreateFrame( "GAMETOOLTIP", "WhatsNext_Condition_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.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.categoryLabel = WhatsNext.AceGUI:Create('Label');
		frame.categoryLabel:SetText("Condition:");
		frame.categoryLabel:SetFont("Fonts\\FRIZQT__.TTF", 13, "")
		frame.categoryLabel:SetWidth(80)
		frame.categoryLabel.label:SetJustifyH("RIGHT")
			
		frame.categoryDropdown = self.AceGUI:Create("Dropdown")
		
		local categoryList = {};
		local categoryPairs= {}
		local categories = {}

		for i, class in pairs(WhatsNext.CLASSES) do		
			local localizedClass = WhatsNextLocal:Localize(class)
			categoryPairs[class] = WhatsNext.CLASS_COLOR_CODES[class]..localizedClass.."|r"
			categories[class] = "0"..localizedClass
			tinsert(categoryList,class)
		end

		
		for i, catagory in ipairs(WhatsNext:GetCheckCategories()) do
			if not tContains(categoryList,catagory)  then
				categoryPairs[catagory] = catagory
				categories[catagory] = "1"..catagory
				tinsert(categoryList,catagory)
			end
		end
		
		
		table.sort(categoryList,function(a,b)
			return categories[b] > categories[a]
		end)
		
		frame.categoryDropdown:SetList(categoryPairs,categoryList)
		frame.categoryDropdown:SetCallback("OnValueChanged", onCategoryChange)
		frame.categoryDropdown:SetWidth(150)

		frame.checkDropdown = self.AceGUI:Create("Dropdown")
		frame.checkDropdown:SetWidth(575)
		frame.checkDropdown:SetCallback("OnValueChanged",onCheckChange)
		
		frame.arguementsGroups = self.AceGUI:Create("InlineGroup")
		frame.arguementsGroups:SetFullWidth(true)
		frame.arguementsGroups:SetLayout("Flow")

		frame:AddChild(createSpacer())
		frame:AddChild(frame.categoryDropdown)
		frame:AddChild(frame.checkDropdown)
		frame:AddChild(frame.arguementsGroups)
		
		frame.categoryDropdown:SetValue(categoryList[1])
	end
	
	--self.conditionFrame:SetCallback("OnHide", cancelFunction)
	self.conditionFrame:SetCallback("OnClose", cancelFunction)

	WhatsNext_ShowOptionsScreen(WhatsNext.conditionFrame.frame)
	self.conditionFrame.confirmFunction = confirmFunction
	self.conditionFrame.cancelFunction = cancelFunction
	self.conditionFrame.sourceIndex = sourceIndex
	self.conditionFrame.condition = condition and DeepCopy(condition) or {type="In Range",checks={}}
	self.conditionFrame.categoryDropdown:SetValue(self:GetCheckCategory(self.conditionFrame.condition.type))
	
	onCategoryChange(self.conditionFrame.categoryDropdown,nil,self.conditionFrame.categoryDropdown:GetValue())
end