local _, T = ...
local L, NIL = T.L, {}

local cfgFrame, cfgControls = CreateFrame("Frame"), {}
	cfgFrame:Hide()
	cfgFrame.name = "Ogri'Lazy"
local cfgFrameHeader = cfgFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightHuge") do
	cfgFrameHeader:SetPoint("TOPLEFT", 7, -22)
	cfgFrameHeader:SetText(cfgFrame.name)
	local t = cfgFrame:CreateTexture(nil, "ARTWORK")
	t:SetAtlas("Options_HorizontalDivider", true)
	t:SetPoint("TOP", 0, -50)
end
local cfgDefaults = CreateFrame("Button", nil, cfgFrame, "UIPanelButtonTemplate")
	cfgDefaults:SetPoint("TOPRIGHT", -36, -16)
	cfgDefaults:SetSize(96, 22)
	cfgDefaults:SetText(DEFAULTS)
	cfgDefaults:SetScript("OnClick", function(self)
		cfgFrame:OnDefault()
		PlaySound(SOUNDKIT.U_CHAT_SCROLL_BUTTON)
	end)

local function cfgCheckboxOnClick(self)
	local isChecked = not not self:GetChecked()
	if self.oldValue == nil then
		local ov = _G[self.setting]
		self.oldValue = ov == nil and NIL or ov
	end
	_G[self.setting] = isChecked
	T.OnSettingChange()
	PlaySound(SOUNDKIT[isChecked and "IG_MAINMENU_OPTION_CHECKBOX_ON" or "IG_MAINMENU_OPTION_CHECKBOX_OFF"])
end
local function updateCheckButtonHitRect(self)
	local b = self:GetParent()
	b:SetHitRectInsets(0, -self:GetStringWidth()-5, 4, 4)
end
local function cfgSpawnCheckbox(setting, text)
	local r = CreateFrame("CheckButton", nil, cfgFrame, "InterfaceOptionsCheckButtonTemplate")
	hooksecurefunc(r.Text, "SetText", updateCheckButtonHitRect)
	r.setting = setting
	r.Text:SetFontObject(GameFontNormal)
	r.Text:ClearAllPoints()
	r.Text:SetPoint("LEFT", r, "RIGHT", 2, 0)
	r.Text:SetText(text)
	r:SetScript("OnClick", cfgCheckboxOnClick)
	cfgControls[#cfgControls+1] = r
	return r
end
local function cfgSpawnSlider(setting, loLabel, hiLabel)
	local s, t = CreateFrame("Slider", nil, cfgFrame,"MinimalSliderTemplate")
	s:SetObeyStepOnDrag(true)
	s:SetWidth(250)
	t = s:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	t, s.text = s:CreateFontString(nil, "OVERLAY"), t
	t, s.lo = s:CreateFontString(nil, "OVERLAY"), t
	s.hi = t
	s.lo:SetFontObject(GameFontHighlightSmall)
	s.hi:SetFontObject(GameFontHighlightSmall)
	s.lo:SetTextColor(0.8, 0.8, 0.8)
	s.hi:SetTextColor(0.8, 0.8, 0.8)
	s.lo:SetPoint("RIGHT", s, "LEFT", -2, 1)
	s.hi:SetPoint("LEFT", s, "RIGHT", 2, 1)
	s.lo:SetText(loLabel or LOW)
	s.hi:SetText(hiLabel or HIGH)
	s.setting = setting
	cfgControls[#cfgControls+1] = s
	return s, 4, s:GetHeight()/2
end
local cfgSpawnBinder do
	local function Relic_KeysetDisarm(btn)
		btn:UnlockHighlight()
		btn:SetScript("OnKeyDown", nil)
		btn:SetScript("OnGamePadButtonDown", nil)
		btn:EnableKeyboard(false)
		btn:EnableGamePadButton(false)
		btn:GetParent().keysetActive = nil
	end
	local unbindableKeys = {
		UNKNOWN=1, ESCAPE=1, ALT=1, SHIFT=1, META=1,
		LALT=1, LCTRL=1, LSHIFT=1, LMETA=1,
		RALT=1, RCTRL=1, RSHIFT=1, RMETA=1,
		PADRSTICKUP=1, PADRSTICKDOWN=1, PADRSTICKLEFT=1, PADRSTICKRIGHT=1,
		PADLSTICKUP=1, PADLSTICKDOWN=1, PADLSTICKLEFT=1, PADLSTICKRIGHT=1,
	}
	local function Relic_KeysetListen(self, arg1)
		if arg1 == "ESCAPE" then
			Relic_KeysetDisarm(self)
			return
		elseif unbindableKeys[arg1] then
			return
		end
		self.oldValue = self.oldValue == nil and self:GetText() or self.oldValue
		local bind = (IsAltKeyDown() and "ALT-" or "") ..  (IsControlKeyDown() and "CTRL-" or "") .. (IsShiftKeyDown() and "SHIFT-" or "") .. (IsMetaKeyDown() and "META-" or "") .. arg1
		self:SetText(bind)
		T.SetKeyBinding(self.bindIndex, bind)
		T.OnSettingChange()
		Relic_KeysetDisarm(self)
		PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
	end
	local function Relic_KeysetClick(self)
		PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
		local oldKeySet = self:GetParent().keysetActive
		if oldKeySet then
			Relic_KeysetDisarm(oldKeySet)
			if oldKeySet == self then
				return
			end
		end
		self:LockHighlight()
		self:GetParent().keysetActive = self
		self:SetScript("OnKeyDown", Relic_KeysetListen)
		self:SetScript("OnGamePadButtonDown", Relic_KeysetListen)
		self:EnableKeyboard(true)
		self:EnableGamePadButton(true)
	end
	function cfgSpawnBinder(index, ofsy, text)
		local btn = CreateFrame("Button", nil, cfgFrame, "UIPanelButtonTemplate")
		btn.lbl = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalLeft")
		btn:SetSize(185, 22)
		btn:SetPoint("TOPLEFT", 250, ofsy)
		btn.lbl:SetPoint("LEFT", -225, 0)
		btn.lbl:SetText(text)
		btn.bindIndex = index
		btn:SetScript("OnClick", Relic_KeysetClick)
		btn:RegisterForClicks("AnyUp")
		cfgControls[#cfgControls+1] = btn
		return btn
	end
end

local cfgShowHelpTooltip = cfgSpawnCheckbox("Relic_ShowTooltip", L"Show help tooltips")
	cfgShowHelpTooltip:SetPoint("TOPLEFT", 20, -60)

local cfgEnableHotkeys = cfgSpawnCheckbox("Relic_EnableHotkeys", L"Enable hotkeys while Ogri'Lazy is shown")
	cfgEnableHotkeys:SetPoint("TOPLEFT", 20, -84)

local cfgUnbindInCombat = cfgSpawnCheckbox("Relic_UnbindCombat", L"Disable Ogri'Lazy hotkeys while in combat")
	cfgUnbindInCombat:SetPoint("TOPLEFT", 20, -108)

local cfgScale = cfgSpawnSlider("Relic_Scale", "1.0", "2.5") do
	cfgScale:SetMinMaxValues(1, 2.5)
	cfgScale:SetValueStep(0.05)
	cfgScale:SetPoint("TOPLEFT", 250, -136)
	cfgScale:SetScript("OnValueChanged", function(self, v, isUserChange)
		if isUserChange then
			if self.oldValue == nil then
				local ov = _G[self.setting]
				self.oldValue = ov == nil and NIL or ov
			end
			_G[self.setting] = v
			T.OnSettingChange()
		end
	end)
	local label = cfgScale:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	label:SetText(UI_SCALE)
	label:SetPoint("LEFT", -225, 0)
end

local cfgKeybindingsHeader = cfgFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightMedium")
	cfgKeybindingsHeader:SetPoint("TOPLEFT", 15, -159-24)
	cfgKeybindingsHeader:SetText(SETTINGS_KEYBINDINGS_LABEL)

local cfgGreenButton  = cfgSpawnBinder(1, -179-24, L"Add Green Relic")
local cfgYellowButton = cfgSpawnBinder(2, -203-24, L"Add Yellow Relic")
local cfgBlueButton   = cfgSpawnBinder(3, -227-24, L"Add Blue Relic")
local cfgRedButton    = cfgSpawnBinder(4, -251-24, L"Add Red Relic")

local function unwrap(v)
	if v == NIL then
		return nil
	end
	return v
end
function cfgFrame.sync()
	local smin, smax = cfgScale:GetMinMaxValues()
	cfgShowHelpTooltip:SetChecked(Relic_ShowTooltip ~= false)
	cfgUnbindInCombat:SetChecked(Relic_UnbindCombat ~= false)
	cfgEnableHotkeys:SetChecked(Relic_EnableHotkeys ~= false)
	cfgScale:SetValue(math.min(smax, math.max(smin, tonumber(Relic_Scale) or 1)))
	local t = T.GetKeyBindings()
	cfgGreenButton:SetText(t[1] or "")
	cfgYellowButton:SetText(t[2] or "")
	cfgBlueButton:SetText(t[3] or "")
	cfgRedButton:SetText(t[4] or "")
end
function cfgFrame.OnCommit()
	for i=1,#cfgControls do
		cfgControls[i].oldValue = nil
	end
end
function cfgFrame.cancel()
	for i=1,#cfgControls do
		i = cfgControls[i]
		local ov = i.oldValue
		if i.setting and ov ~= nil then
			_G[i.setting] = unwrap(ov)
		elseif i.bindIndex and ov ~= nil then
			T.SetKeyBinding(i.bindIndex, unwrap(ov))
		end
		i.oldValue = nil
	end
	T.OnSettingChange()
	cfgFrame.sync()
end
function cfgFrame.OnDefault()
	local t = T.GetKeyBindings()
	for i=1,#cfgControls do
		local c = cfgControls[i]
		if c.setting and c.oldValue == nil then
			local ov = _G[c.setting]
			c.oldValue = ov == nil and NIL or ov
		elseif c.bindIndex and c.oldValue == nil then
			c.oldValue = t[c.bindIndex]
		end
	end
	Relic_ShowTooltip, Relic_UnbindCombat, Relic_EnableHotkeys, Relic_KeyBindings, Relic_Scale = nil
	T.OnSettingChange()
	cfgFrame.sync()
end

cfgFrame:SetScript("OnShow", cfgFrame.sync)
local category = Settings.RegisterCanvasLayoutCategory(cfgFrame, cfgFrame.name)
Settings.RegisterAddOnCategory(category)
function T.OpenOgriLazyConfig()
	Settings.OpenToCategory(category.ID)
end