local addonName, ItemProfConstants = ...

local frame = CreateFrame( "Frame" )
frame.name = addonName

local profsCheck
local questCheck
local vendorCheck
local dmfCheck
local iconSizeSlider

local PROF_CHECK = table.create( 9 ) -- preallocating?
local QUEST_CHECK = table.create( 20 )

local userVariables


local function SaveAndQuit() 
	
	local profFlags = 0
	for i=1, #PROF_CHECK do
		if PROF_CHECK[ i ]:GetChecked() then
			profFlags = profFlags + PROF_CHECK[ i ]:GetID()
		end
	end

	local questFlags = 1		-- Always track quest flag 'Q'
	for i=1, #QUEST_CHECK do
		if QUEST_CHECK[ i ]:GetChecked() then
			questFlags = questFlags + QUEST_CHECK[ i ]:GetID()
		end
	end

	userVariables.showProfs = profsCheck:GetChecked()
	userVariables.showQuests = questCheck:GetChecked()
	userVariables.profFlags = profFlags
	userVariables.questFlags = questFlags
	userVariables.includeVendor = vendorCheck:GetChecked()
	userVariables.iconSize = iconSizeSlider:GetValue()
	userVariables.showDMF = dmfCheck:GetChecked()
	ItemProfConstants:ConfigChanged( userVariables )
end


local function ToggleProfCheckbox() 
	-- Enable/disable profession tracking
	local isChecked = profsCheck:GetChecked()
	for i=1, #PROF_CHECK do
		PROF_CHECK[ i ]:SetEnabled( isChecked )
	end
end

local function ToggleQuestCheckbox() 
	-- Enable/disable quest tracking
	local isChecked = questCheck:GetChecked()
	for i=1, #QUEST_CHECK do
		QUEST_CHECK[ i ]:SetEnabled( isChecked )
	end
end


local function RefreshWidgets()
	-- Sync the widgets with the config variables
	profsCheck:SetChecked( userVariables.showProfs )
	questCheck:SetChecked( userVariables.showQuests )
	vendorCheck:SetChecked( userVariables.includeVendor )
	dmfCheck:SetChecked( userVariables.showDMF )
	local profFlags = userVariables.profFlags
	local questFlags = userVariables.questFlags
	iconSizeSlider:SetValue( userVariables.iconSize )
		
	-- Update the profession checkboxes
	for i=1, #PROF_CHECK do
		local isSet = bit.band( profFlags, PROF_CHECK[ i ]:GetID() )
		PROF_CHECK[ i ]:SetChecked( isSet ~= 0 )
	end
	-- Update the quest checkboxes
	for i=1, #QUEST_CHECK do 
		local isSet = bit.band( questFlags, QUEST_CHECK[ i ]:GetID() )
		QUEST_CHECK[ i ]:SetChecked( isSet ~= 0 )
	end

	-- Set checkboxes enabled/disabled
	ToggleProfCheckbox()
	ToggleQuestCheckbox()
end


local function IconSizeChanged( self, value ) 
	-- Called when the icon slider widget changes value
	self.ValueText:SetText( value )
	self.IconPreview:SetSize( value, value )
end


local function InitVariables( self, event, loadedName )
	
	if loadedName ~= self.name then
		return
	end

	self:UnregisterEvent( "ADDON_LOADED" )

	local configRealm = GetRealmName()
	local configChar = UnitName( "player" )
	
	if not ItemTooltipIconsConfig then
		ItemTooltipIconsConfig = {}
	end
	
	if not ItemTooltipIconsConfig[ configRealm ] then
		ItemTooltipIconsConfig[ configRealm ] = {}
	end
	
	if not ItemTooltipIconsConfig[ configRealm ][ configChar ] then
		ItemTooltipIconsConfig[ configRealm ][ configChar ] = {}
	end
	
	userVariables = ItemTooltipIconsConfig[ configRealm ][ configChar ]

	if next( userVariables ) == nil then -- Check for table entry
		-- Default config
		userVariables.showProfs = true
		userVariables.showQuests = true
		userVariables.profFlags = 0xFFF
		userVariables.questFlags = 0xFFFFFF
		userVariables.includeVendor = false 
		userVariables.iconSize = 16
		userVariables.showDMF = true
		-- New entries need init
	end
	
	RefreshWidgets()
	ItemProfConstants:ConfigChanged( userVariables )
end


local function CreateCheckbox( name, label, parent )

	local check = CreateFrame( "CheckButton", name, parent, "ChatConfigCheckButtonTemplate" )
	check.Text:SetText( label )
	check.Text:SetPointsOffset( 6, 1 )
	return check
end


local function CreateProfessionWidgets( profConfig ) 

	profsCheck = CreateCheckbox( "ToggleAllProfs", "Enable Profession Icons", profConfig )
	profsCheck:SetPoint( profConfig:GetPointByName( "TOPLEFT" ) )
	profsCheck.tooltip = "If enabled profession icons will be displayed on items that are crafting materials"
	profsCheck:SetScript( "OnClick", ToggleProfCheckbox )
	
	PROF_CHECK[ 1 ] = CreateCheckbox( "ToggleCook", "Cooking", profConfig )
	PROF_CHECK[ 2 ] = CreateCheckbox( "ToggleFAid", "First Aid", profConfig )
	PROF_CHECK[ 3 ] = CreateCheckbox( "ToggleAlc", "Alchemy", profConfig )
	PROF_CHECK[ 4 ] = CreateCheckbox( "ToggleBS", "Blacksmithing", profConfig )
	PROF_CHECK[ 5 ] = CreateCheckbox( "ToggleEnc", "Enchanting", profConfig )
	PROF_CHECK[ 6 ] = CreateCheckbox( "ToggleEng", "Engineering", profConfig )
	PROF_CHECK[ 7 ] = CreateCheckbox( "ToggleLW", "Leatherworking", profConfig )
	PROF_CHECK[ 8 ] = CreateCheckbox( "ToggleTail", "Tailoring", profConfig )

	-- Align in rows of 3 top to bottom
	PROF_CHECK[ 1 ]:SetPoint( "TOPLEFT", profsCheck, "BOTTOMLEFT", 25, 5 )
	PROF_CHECK[ 2 ]:SetPoint( "LEFT", PROF_CHECK[ 1 ], "RIGHT", 200, 0 )
	PROF_CHECK[ 3 ]:SetPoint( "LEFT", PROF_CHECK[ 2 ], "RIGHT", 200, 0 )
	PROF_CHECK[ 4 ]:SetPoint( "TOPLEFT", PROF_CHECK[ 1 ], "BOTTOMLEFT", 0, 5 )
	PROF_CHECK[ 5 ]:SetPoint( "LEFT", PROF_CHECK[ 4 ], "RIGHT", 200, 0 )
	PROF_CHECK[ 6 ]:SetPoint( "LEFT", PROF_CHECK[ 5 ], "RIGHT", 200, 0 )
	PROF_CHECK[ 7 ]:SetPoint( "TOPLEFT", PROF_CHECK[ 4 ], "BOTTOMLEFT", 0, 5 )
	PROF_CHECK[ 8 ]:SetPoint( "LEFT", PROF_CHECK[ 7 ], "RIGHT", 200, 0 )

	-- Append expansion profession
	if LE_EXPANSION_LEVEL_CURRENT > 0 then
		PROF_CHECK[ 9 ] = CreateCheckbox( "ToggleJC", "Jewelcrafting", profConfig )
		PROF_CHECK[ 9 ]:SetPoint( "LEFT", PROF_CHECK[ 8 ], "RIGHT", 200, 0 )
	end

	-- Precalculate the bit mask used to toggle flag
	local len = #PROF_CHECK
	for i=1, len do
		PROF_CHECK[ i ]:SetID( bit.lshift( 1, i-1 ) )
	end

	profConfig:SetPoint( "BOTTOM", PROF_CHECK[ len ] )
end


local function CreateQuestWidgets( questConfig ) 
	
	questCheck = CreateCheckbox( "ToggleAllQuests", "Enable Quest Icons", questConfig )
	questCheck:SetPoint( questConfig:GetPointByName( "TOPLEFT" ) )
	questCheck.tooltip = "If enabled quest icons will be displayed on items that are needed by quests"
	questCheck:SetScript( "OnClick", ToggleQuestCheckbox )

	QUEST_CHECK[ 1 ] = CreateCheckbox( "ToggleAllianceQ", "Alliance", questConfig )
	QUEST_CHECK[ 1 ]:SetPoint( "TOPLEFT", "ToggleAllQuests", "BOTTOMLEFT", 25, 5 )
	QUEST_CHECK[ 2 ] = CreateCheckbox( "ToggleHordeQ", "Horde", questConfig )
	QUEST_CHECK[ 2 ]:SetPoint( "TOPLEFT", "ToggleAllianceQ", "BOTTOMLEFT", 0, 5 )

	local classQuestLabel = questConfig:CreateFontString( "ClassQuestLabel", "OVERLAY", nil )
	classQuestLabel:SetFont( "Fonts\\FRIZQT__.TTF", 14, "OUTLINE" )
	classQuestLabel:SetTextColor( 1, 0.85, 0.15 )
	classQuestLabel:SetPoint( "TOPLEFT", "ToggleHordeQ", "BOTTOMLEFT", 0, -10 )
	classQuestLabel:SetText( "Class Quests" )

	QUEST_CHECK[ 3 ] = CreateCheckbox( "ToggleDruidQ", "Druid", questConfig )
	QUEST_CHECK[ 3 ]:SetPoint( "TOPLEFT", "ClassQuestLabel", "BOTTOMLEFT", 0, -5 )
	QUEST_CHECK[ 4 ] = CreateCheckbox( "ToggleHunterQ", "Hunter", questConfig )
	QUEST_CHECK[ 4 ]:SetPoint( "LEFT", "ToggleDruidQ", "RIGHT", 200, 0 )
	QUEST_CHECK[ 5 ] = CreateCheckbox( "ToggleMageQ", "Mage", questConfig )
	QUEST_CHECK[ 5 ]:SetPoint( "LEFT", "ToggleHunterQ", "RIGHT", 200, 0 )

	QUEST_CHECK[ 6 ] = CreateCheckbox( "TogglePaladinQ", "Paladin", questConfig )
	QUEST_CHECK[ 6 ]:SetPoint( "TOPLEFT", "ToggleDruidQ", "BOTTOMLEFT", 0, 5 )
	QUEST_CHECK[ 7 ] = CreateCheckbox( "TogglePriestQ", "Priest", questConfig )
	QUEST_CHECK[ 7 ]:SetPoint( "LEFT", "TogglePaladinQ", "RIGHT", 200, 0 )
	QUEST_CHECK[ 8 ] = CreateCheckbox( "ToggleRogueQ", "Rogue", questConfig )
	QUEST_CHECK[ 8 ]:SetPoint( "LEFT", "TogglePriestQ", "RIGHT", 200, 0 )

	QUEST_CHECK[ 9 ] = CreateCheckbox( "ToggleShamanQ", "Shaman", questConfig )
	QUEST_CHECK[ 9 ]:SetPoint( "TOPLEFT", "TogglePaladinQ", "BOTTOMLEFT", 0, 5 )
	QUEST_CHECK[ 10 ] = CreateCheckbox( "ToggleWarlockQ", "Warlock", questConfig )
	QUEST_CHECK[ 10 ]:SetPoint( "LEFT", "ToggleShamanQ", "RIGHT", 200, 0 )
	QUEST_CHECK[ 11 ] = CreateCheckbox( "ToggleWarriorQ", "Warrior", questConfig )
	QUEST_CHECK[ 11 ]:SetPoint( "LEFT", "ToggleWarlockQ", "RIGHT", 200, 0 )

	local profQuestLabel = questConfig:CreateFontString( "ProfQuestLabel", "OVERLAY", nil )
	profQuestLabel:SetFont( "Fonts\\FRIZQT__.TTF", 14, "OUTLINE" )
	profQuestLabel:SetTextColor( 1, 0.85, 0.15 )
	profQuestLabel:SetPoint( "TOPLEFT", "ToggleShamanQ", "BOTTOMLEFT", 0, -10 )
	profQuestLabel:SetText( "Profession Quests" )
	
	QUEST_CHECK[ 12 ] = CreateCheckbox( "ToggleCook", "Cooking", questConfig )
	QUEST_CHECK[ 13 ] = CreateCheckbox( "ToggleFAid", "First Aid", questConfig )
	QUEST_CHECK[ 14 ] = CreateCheckbox( "ToggleAlc", "Alchemy", questConfig )
	QUEST_CHECK[ 15 ] = CreateCheckbox( "ToggleBS", "Blacksmithing", questConfig )
	QUEST_CHECK[ 16 ] = CreateCheckbox( "ToggleEnc", "Enchanting", questConfig )
	QUEST_CHECK[ 17 ] = CreateCheckbox( "ToggleEng", "Engineering", questConfig )
	QUEST_CHECK[ 18 ] = CreateCheckbox( "ToggleLW", "Leatherworking", questConfig )
	QUEST_CHECK[ 19 ] = CreateCheckbox( "ToggleTail", "Tailoring", questConfig )

	-- Align in rows of 3 top to bottom
	QUEST_CHECK[ 12 ]:SetPoint( "TOPLEFT", profQuestLabel, "BOTTOMLEFT", 0, -5 )
	QUEST_CHECK[ 13 ]:SetPoint( "LEFT", QUEST_CHECK[ 12 ], "RIGHT", 200, 0 )
	QUEST_CHECK[ 14 ]:SetPoint( "LEFT", QUEST_CHECK[ 13 ], "RIGHT", 200, 0 )
	QUEST_CHECK[ 15 ]:SetPoint( "TOPLEFT", QUEST_CHECK[ 12 ], "BOTTOMLEFT", 0, 5 )
	QUEST_CHECK[ 16 ]:SetPoint( "LEFT", QUEST_CHECK[ 15 ], "RIGHT", 200, 0 )
	QUEST_CHECK[ 17 ]:SetPoint( "LEFT", QUEST_CHECK[ 16 ], "RIGHT", 200, 0 )
	QUEST_CHECK[ 18 ]:SetPoint( "TOPLEFT", QUEST_CHECK[ 15 ], "BOTTOMLEFT", 0, 5 )
	QUEST_CHECK[ 19 ]:SetPoint( "LEFT", QUEST_CHECK[ 18 ], "RIGHT", 200, 0 )

	if LE_EXPANSION_LEVEL_CURRENT > 0 then
		QUEST_CHECK[ 20 ] = CreateCheckbox( "ToggleJC", "Jewelcrafting", questConfig )
		QUEST_CHECK[ 20 ]:SetPoint( "LEFT", QUEST_CHECK[ 19 ], "RIGHT", 200, 0 )
	end

	-- Precalculate the bit mask used to toggle flag
	local len = #QUEST_CHECK
	for i=1, len do
		QUEST_CHECK[ i ]:SetID( bit.lshift( 1, i ) ) -- bit 0 is Q
	end

	questConfig:SetPoint( "BOTTOM", QUEST_CHECK[ len ] )
end


local function CreateMiscWidgets( miscConfig )

	vendorCheck = CreateCheckbox( "ToggleVendor", "Vendor Items", miscConfig )
	vendorCheck.tooltip = "Display icons on items sold by vendors"
	vendorCheck:SetPoint( miscConfig:GetPointByName( "TOPLEFT" ) )

	dmfCheck = CreateCheckbox( "ToggleDMF", "Darkmoon Faire Ticket Items", miscConfig )
	dmfCheck.tooltip = "Display a ticket icon if the item can be exchanged for Darkmoon Faire tickets"
	dmfCheck:SetPoint( "TOP", vendorCheck, "BOTTOM" )


	iconSizeSlider = CreateFrame( "Slider", "SliderIconSize", miscConfig, "MinimalSliderTemplate" )
	iconSizeSlider:SetPoint( "TOPLEFT", dmfCheck, "BOTTOMLEFT", 0, -20 )
	iconSizeSlider:SetMinMaxValues( 8, 32 )
	iconSizeSlider:SetValueStep( 1 )
	iconSizeSlider:SetStepsPerPage( 1 )
	iconSizeSlider:SetSize( 200, 17 )
	iconSizeSlider:SetObeyStepOnDrag( true )
	iconSizeSlider:SetScript( "OnValueChanged", IconSizeChanged )

	iconSizeSlider.Name = iconSizeSlider:CreateFontString( "Name", "OVERLAY", "GameFontHighlight" ) 
	iconSizeSlider.Name:SetPoint( "BOTTOM", iconSizeSlider, "TOP" )
	iconSizeSlider.Name:SetText( "Icon Size" )

	iconSizeSlider.ValueText = iconSizeSlider:CreateFontString( "ValueText", "OVERLAY", "GameFontHighlight" )
	iconSizeSlider.ValueText:SetPoint( "LEFT", iconSizeSlider, "RIGHT", 16, 0 )

	iconSizeSlider.IconPreview = iconSizeSlider:CreateTexture( "IconPreview", "OVERLAY" )
	iconSizeSlider.IconPreview:SetPoint( "LEFT", iconSizeSlider.ValueText, "RIGHT", 24, 0 )
	iconSizeSlider.IconPreview:SetTexture( 136243 )


	miscConfig:SetPoint( "BOTTOM", iconSizeSlider )
end


frame.Header = frame:CreateFontString( "Header", "OVERLAY", "GameTooltipTextSmall" )
frame.Header:SetPoint( "TOPLEFT", 20, -20 )
frame.Header:SetText( "These options allow you control which icons are displayed on the item tooltips.\nThe quest icon can be filtered to appear only on items needed for quests of specific class/profession." )

-- Frames for each category to simplify alignment
local profConfig = CreateFrame( "Frame", "ConfigProf", frame )
profConfig:SetPoint( "TOPLEFT", frame.Header, "BOTTOMLEFT", 0, -20 )
profConfig:SetPoint( "TOPRIGHT" )

local questConfig = CreateFrame( "Frame", "ConfigQuest", frame )
questConfig:SetPoint( "TOPLEFT", profConfig, "BOTTOMLEFT", 0, -20 )
questConfig:SetPoint( "TOPRIGHT" )

local miscConfig = CreateFrame( "Frame", "ConfigMisc", frame )
miscConfig:SetPoint( "TOPLEFT", questConfig, "BOTTOMLEFT", 0, -20 )
miscConfig:SetPoint( "TOPRIGHT" )

CreateProfessionWidgets( profConfig )
CreateQuestWidgets( questConfig )
CreateMiscWidgets( miscConfig )


frame:Hide()	-- The options menu is calling hide before 1st show
frame:SetScript( "OnEvent", InitVariables )
frame:SetScript( "OnHide", SaveAndQuit )
frame:RegisterEvent( "ADDON_LOADED" )

if Settings and ( Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory ) then
	-- Classic client is now using the modern Settings API
	local category = _G.Settings.RegisterCanvasLayoutCategory( frame, frame.name )
	category.ID = frame.name
	_G.Settings.RegisterAddOnCategory( category )
else
	frame.okay = SaveAndQuit
	--frame:SetScript( "OnShow", RefreshWidgets )
	InterfaceOptions_AddCategory( frame )
end
