-- If you aren't a monk, then disable the addon
if select(2, UnitClass("player")) ~= "MONK" then
	return
end


local f = CreateFrame("frame")
local max_chi = 4
local xpos = 0
local ypos = 0
local r = 0.9686274509803922
local g = 0.674509803921568
local b = 0.1450980392156863
local scale = 1
local hidenocombat = false
local leftanchor = "CENTER"
local chiframes = {}
local duetohide = false
local firstrun = true
local hideDefaultFrames = false
local alpha_value = 1.0

f:SetScript("OnEvent", function(self, event, ...)
    self[event](self, ...)
end)

local function updateChi()
	local power = UnitPower("player", 12)
	local i = 1

	while i <= power do
		chiframes[i]:SetBackdropColor(r, g, b, alpha_value)
		i = 1 + i
	end

	while i <= max_chi do
		chiframes[i]:SetBackdropColor(r, g, b, 0.1)
		i = 1 + i
	end

	if duetohide and power == 0 then
		for i = 1,max_chi do
			chiframes[i]:Hide()
		end
		duetohide = false
	end

end


local function updateFrames()
	for i = 1,max_chi do

		chiframes[i]:SetSize(22, 22)

		chiframes[i]:SetBackdropColor(r, g, b, 0.1)
		chiframes[i]:SetBackdropBorderColor(0, 0, 0, 1)
	 
		if i == 1 then
			chiframes[i]:SetPoint(leftanchor, UIParent, leftanchor, xpos, ypos)
			chiframes[i]:SetScale(scale)

			chiframes[i]:SetMovable(true)
			chiframes[i]:EnableMouse(true)
			chiframes[i]:RegisterForDrag("LeftButton")
			chiframes[i]:SetScript("OnDragStart", function(self)
				if IsAltKeyDown() then
					self:StartMoving()
				end
			end)
			chiframes[i]:SetScript("OnDragStop", function(self)
				self:StopMovingOrSizing()
				anch,_, _, x, y = self:GetPoint(1)
				xpos = x
				SimpleChiDB.xpos = x
				xpos = y
				SimpleChiDB.ypos = y
				leftanchor = anch
				SimpleChiDB.leftanchor = anch

			end)
			

		else
			chiframes[i]:SetPoint("RIGHT", 23, 0)

		end

		if hidenocombat and not InCombatLockdown() then
			duetohide = true
		else
			chiframes[i]:Show()
		end
		

	end
	updateChi()
end

local function initFrames()
	for i = 1,max_chi do
		chiframes[i] = CreateFrame("Frame", "SChiFrame"..i, i == 1 and UIParent or chiframes[i-1])
		chiframes[i]:SetBackdrop({bgFile=[[Interface\ChatFrame\ChatFrameBackground]],edgeFile=[[Interface/Tooltips/UI-Tooltip-Border]],tile=true,tileSize=4,edgeSize=4,insets={left=0.5,right=0.5,top=0.5,bottom=0.5}})
	end
	updateFrames()
end

local function destroyFrames()
	for i = 1,max_chi do
		if chiframes[i] ~= nil then
			chiframes[i]:Hide()
		end
	end
	for i = 1,max_chi do
		if chiframes[i] ~= nil then
			chiframes[i] = nil
		end
	end
	chiframes = {}
end

local function updateNumBoxes()
	local old_max_chi = max_chi
	max_chi = UnitPowerMax("player", 12)
	if max_chi == 0 then
		max_chi = old_max_chi
		return
	end
	if old_max_chi == 5 and max_chi == 4 then
		if chiframes[5] ~= nil then
			chiframes[5]:Hide()
		end
	elseif old_max_chi == 4 and max_chi == 5 then
		if chiframes[5] ~= nil then
			chiframes[5]:Show()
		else
			chiframes[5] = CreateFrame("Frame", "SChiFrame5", chiframes[4])
			chiframes[5]:SetBackdrop({bgFile=[[Interface\ChatFrame\ChatFrameBackground]],edgeFile=[[Interface/Tooltips/UI-Tooltip-Border]],tile=true,tileSize=4,edgeSize=4,insets={left=0.5,right=0.5,top=0.5,bottom=0.5}})
			chiframes[5]:SetSize(22, 22)
			chiframes[5]:SetBackdropColor(r, g, b, 0.1)
			chiframes[5]:SetBackdropBorderColor(0, 0, 0, 1)
			chiframes[5]:SetPoint("RIGHT", 23, 0)
			if UnitPower("player", 12) == 0 and hidenocombat and not InCombatLockdown() then
				chiframes[5]:Hide()
			else
				chiframes[5]:Show()
			end


			updateChi()
		end
	elseif old_max_chi ~= max_chi then
		destroyFrames()
		initFrames()
	end
end

function Chi_ColorPickCallback(restore)
	if restore then
		r, g, b = unpack(restore)
	else
		r, g, b = ColorPickerFrame:GetColorRGB();
	end
	
	SimpleChiDB.r = r
	SimpleChiDB.g = g
	SimpleChiDB.b = b

	updateFrames()
end

function f:PLAYER_ENTERING_WORLD()
	updateChi()
end

function f:UNIT_POWER(unit, type)
	if type == "CHI" and unit == "player" then
		if firstrun then
			updateNumBoxes()
			firstrun = false
		end
		updateChi()
	end
end

function f:UNIT_MAXPOWER()
	updateNumBoxes()
end

function f:PLAYER_TALENT_UPDATE()
	updateNumBoxes()
end
	
function f:PLAYER_REGEN_DISABLED()
	updateNumBoxes()
	for i = 1,max_chi do
		chiframes[i]:Show()
	end
	duetohide = false
end

function f:PLAYER_REGEN_ENABLED()
	if hidenocombat then
		if UnitPower("player", 12) == 0 then
			for i = 1,max_chi do
				chiframes[i]:Hide()
			end
		else
			duetohide = true
		end
	end
end


function f:ADDON_LOADED(addon)
	if addon ~= "SimpleChi" then return end
	if select(2, UnitClass("player")) ~= "MONK" then
		return
	end

	local defaults = {
		xpos = 0,
		ypos = 0,
		r = 0.9686274509803922,
		g = 0.6745098039215687,
		b = 0.1450980392156863,
		scale = 1,
		leftanchor = "CENTER",
		hidenocombat = false,
		hideDefaultFrames = false,
		alpha_value = 1.0
	}
		
	SimpleChiDB = SimpleChiDB or {}
		
	for k,v in pairs(defaults) do
		if SimpleChiDB[k] == nil then
			SimpleChiDB[k] = v
		end
	end


	SLASH_SC1, SLASH_SC2 = "/sc", "/simplechi"
	SlashCmdList.SC = function(txt)
		local cmd, msg = txt:match("^(%S*)%s*(.-)$");
		cmd = string.lower(cmd)
		msg = string.lower(msg)

		if cmd == "reset" then
			xpos = 0
			ypos = 0
			r = 0.9686274509803922
			g = 0.674509803921568
			b = 0.1450980392156863
			scale = 1
			leftanchor = "CENTER"
			alpha_value = 1.0
			SimpleChiDB.xpos = 0
			SimpleChiDB.ypos = 0
			SimpleChiDB.r = 0.9686274509803922
			SimpleChiDB.g = 0.674509803921568
			SimpleChiDB.b = 0.1450980392156863
			SimpleChiDB.scale = 1
			SimpleChiDB.leftanchor = "CENTER"
			SimpleChiDB.alpha_value = 1.0
			
			destroyFrames()
			initFrames()

			print("Frame reset to the center, you can now move it to the desired position.")

		elseif cmd == "scale" then
			local num = tonumber(msg)
			if num then
				scale = num
				SimpleChiDB.scale = num

				updateFrames()
			else
				print("Not a valid scale! Scale has to be a number, recommended to be between 0.5 and 3")
			end
		elseif cmd == "alpha" then
			local num = tonumber(msg)
			if num then
				if num <= 1.0 and num >= 0.2 then
					alpha_value = num
					SimpleChiDB.alpha_value = num

					updateChi()
				else
					print("Not a valid alpha value! Alpha has to be a number, and must be between 0.2 and 1")
				end
			else
				print("Not a valid alpha value! Alpha has to be a number, and must be between 0.2 and 1")
			end
		elseif cmd == "color" or cmd == "colour" then
			ColorPickerFrame:SetColorRGB(r,g,b)
			ColorPickerFrame.previousValues = {r,g,b}
			ColorPickerFrame.func, ColorPickerFrame.opacityFunc, ColorPickerFrame.cancelFunc = Chi_ColorPickCallback, Chi_ColorPickCallback, Chi_ColorPickCallback
			ColorPickerFrame:Hide() -- apparently needed...
			ColorPickerFrame:Show()
		elseif cmd  == "nocombat" then
			if msg == "on" then
				hidenocombat = false
				SimpleChiDB.hidenocombat = false
				duetohide = false
				f:UnregisterEvent("PLAYER_REGEN_ENABLED")
				f:UnregisterEvent("PLAYER_REGEN_DISABLED")
				for i = 1,max_chi do
					chiframes[i]:Show()
				end
			elseif msg == "off" then
				hidenocombat = true
				SimpleChiDB.hidenocombat = true
				f:RegisterEvent("PLAYER_REGEN_ENABLED")
				f:RegisterEvent("PLAYER_REGEN_DISABLED")

				if not InCombatLockdown() then
					for i = 1,max_chi do
						chiframes[i]:Hide()
					end
				end

			else
				print("|cffff0000Invalid command!|r Use |cff3399FF/sc nocombat off|r or |cff3399FF/sc nocombat on|r")
			end

		elseif cmd == "hidedefault" then
			if msg == "on" then
				hideDefaultFrames = true
				SimpleChiDB.hideDefaultFrames = true

				MonkHarmonyBar:Hide()
				MonkHarmonyBar.Show = function() end 
			elseif msg == "off" then
				hideDefaultFrames = false
				SimpleChiDB.hideDefaultFrames = false
			
				print("|cff3399FFSetting updated, you will however need to re-log or reload UI before the changes will take place.|r")
			else
				print("Invalid usage, use |cff3399FF/sc hidedefault|r |cff00cf00on|r | |cffff0000off|r  ")
			end

		else
			print("|cff3399FF/sc|r usage:")
			print("|cff3399FF/sc reset|r Resets the addon back to default settings. Use if you can't see the frame and/or dragged it out of the screen.")
			print("|cff3399FF/sc color|r Open the color picker window.")
			print("|cff3399FF/sc scale|r Change the scale of the addon (default: 1, don't use values larger than 3)")
			print("|cff3399FF/sc alpha|r Change the alpha of the chi boxes (while you have chi), default value: 1, value must be between 0.2 and 1")
			print("|cff3399FF/sc nocombat|r |cff00cf00on|r | |cffff0000off|r Whether the boxes should be shown outside combat or not.")
			print("|cff3399FF/sc hidedefault|r |cff00cf00on|r | |cffff0000off|r Whether the Blizzard default chi frame should be shown or not.")
			print("|cff33FF99To move the boxes:|r Alt+Left mouse button on the leftmost box to drag it.")
		end

	end

	xpos = SimpleChiDB.xpos
	ypos = SimpleChiDB.ypos
	r = SimpleChiDB.r
	g = SimpleChiDB.g
	b = SimpleChiDB.b
	scale = SimpleChiDB.scale
	leftanchor = SimpleChiDB.leftanchor
	hidenocombat = SimpleChiDB.hidenocombat
	hideDefaultFrames = SimpleChiDB.hideDefaultFrames
	alpha_value = SimpleChiDB.alpha_value

	max_chi = UnitPowerMax("player", 12)
	if max_chi == 0 then
		max_chi = 4
	end


	if hidenocombat and not InCombatLockdown() then
		duetohide = true
	end

	initFrames()

	f:RegisterEvent("UNIT_POWER")
	f:RegisterEvent("PLAYER_ENTERING_WORLD")
	f:RegisterEvent("UNIT_MAXPOWER")
	f:RegisterEvent("PLAYER_TALENT_UPDATE")
	f:RegisterEvent("PLAYER_REGEN_DISABLED")

	if hidenocombat then
		f:RegisterEvent("PLAYER_REGEN_ENABLED")
	end


	if hideDefaultFrames then
		MonkHarmonyBar:Hide()
		MonkHarmonyBar.Show = function() end 
	end


end

f:RegisterEvent("ADDON_LOADED")
