local _G = _G
local pairs = _G.pairs
local GetTime = _G.GetTime
local UnitBuff = _G.UnitBuff
local IRF3 = _G[...]

local SL = IRF3.GetSpellName
local testTime = GetTime()-0.00001
local afterCPU = 0
local afterTestCPU = 0
local updateFrequency = 1
local updateTimer = 0
local InvenRaidFrames3CPUUsage = nil

local function formatNumber(number,pattern)
	local isBig = number>=1000
  number = string.format(pattern,number)
	if isBig then
	  local subCount
	  repeat
	    number,subCount = number:gsub("^(-?%d+)(%d%d%d)","%1,%2")
	  until subCount==0
	end
  return number
end

local function InitText()
  InvenRaidFrames3CPUUsage.TextTitle = {}
  InvenRaidFrames3CPUUsage.Text = {}
  InvenRaidFrames3CPUUsage.CPU = {}
  InvenRaidFrames3CPUUsage.CPUCount = {}
end

local function AddTextBar(index, text, JustifyH, PointV, PointX, PointY, addX)
  InvenRaidFrames3CPUUsage.TextTitle[index] = InvenRaidFrames3CPUUsage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  InvenRaidFrames3CPUUsage.TextTitle[index]:SetWidth(200)
  InvenRaidFrames3CPUUsage.TextTitle[index]:SetJustifyH(JustifyH)
  InvenRaidFrames3CPUUsage.TextTitle[index]:SetWordWrap(false)
  InvenRaidFrames3CPUUsage.TextTitle[index]:SetText(text)
  InvenRaidFrames3CPUUsage.TextTitle[index]:SetPoint(PointV, PointX, PointY)
  InvenRaidFrames3CPUUsage.Text[index] = InvenRaidFrames3CPUUsage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  InvenRaidFrames3CPUUsage.Text[index]:SetWidth(200)
  InvenRaidFrames3CPUUsage.Text[index]:SetJustifyH(JustifyH)
  InvenRaidFrames3CPUUsage.Text[index]:SetWordWrap(false)
  InvenRaidFrames3CPUUsage.Text[index]:SetText("")
  InvenRaidFrames3CPUUsage.Text[index]:SetPoint(PointV, PointX + addX, PointY)
  InvenRaidFrames3CPUUsage.CPU[index] = 0
  InvenRaidFrames3CPUUsage.CPUCount[index] = 0
end

local function setBackgroundPoint(bg, context, inset, top, height)
	local minset = inset * (-1);
	bg:ClearAllPoints();
	bg:SetPoint("BOTTOMLEFT", context, "BOTTOMLEFT", minset, inset + top - height);
	bg:SetPoint("TOPLEFT", context, "TOPLEFT", minset, inset + top);
	bg:SetPoint("TOPRIGHT", context, "TOPRIGHT", inset, inset + top);
	bg:SetPoint("BOTTOMRIGHT", context, "BOTTOMRIGHT", inset, inset + top - height);
end

local function setBackgroundLevel(bg, context)
	local level = context:GetFrameLevel();
	bg:SetFrameLevel(level);
	context:SetFrameLevel(level+1);
end

local function setBackground(bg, frame, inset, top, height)
	setBackgroundPoint(bg, frame, inset, top, height)
	setBackgroundLevel(bg, frame);
end

local InvenRaidFrames3_ColorBorder = {
	bgFile = "Interface/Tooltips/UI-Tooltip-Background",
	edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
	tile = true,
	tileSize = 20,
	edgeSize = 15,
	insets = { left = 3, right = 3, top = 3, bottom = 3 } 
}

local function setBackColor(frame, mode)
  if IRF3.disableLibAuras then
    mode = mode + 1
  else
    mode = mode + 3
  end
  if mode == 1 then
    frame:SetBackdropColor(.3, .3, .3, 1);  -- 비활성
	elseif mode == 2 then
    frame:SetBackdropColor(.4, .4, .4, 1);  -- 비활성 마우스오버
	elseif mode == 3 then
    frame:SetBackdropColor(.7, .7, .7, 1);  -- 활성화
	else 
    frame:SetBackdropColor(.8, .8, .8, 1);  -- 활성화 마우스오버
	end
end

local function setColor(frame)
	frame:SetBackdropBorderColor(1, 1, 0, 1);
	setBackColor(frame, 1);
end
	
local function setBorder(frame)
	if (not WindActionPetConfig or WindActionPetConfig[6]) then 
		frame:SetBackdrop(InvenRaidFrames3_ColorBorder);
		setColor(frame);
	else 
		InvenRaidFrames3CPUUsage:SetBackdrop(nil); 
	end
end

local function SetItem(index, func)
  local rTime, rCount = GetFunctionCPUUsage(func, true)
  InvenRaidFrames3CPUUsage.Text[index]:SetText(formatNumber(rTime - InvenRaidFrames3CPUUsage.CPU[index],"%.2f\124cffffd200ms/s  ").. rCount - InvenRaidFrames3CPUUsage.CPUCount[index] .."/"..rCount.."회")
  InvenRaidFrames3CPUUsage.CPU[index] = rTime
  InvenRaidFrames3CPUUsage.CPUCount[index] = rCount
end

local function InitUI()
  InitText()
  local x = -5  
  AddTextBar("TITLE", "LibAuras ON", "CENTER", "TOP", 0, -6, 0)
  AddTextBar("MEM", "Mem : ", "LEFT", "TOP", x + 0, -20, 70)
  AddTextBar("CPU", "CPU : ", "LEFT", "TOP", x + 0, -32, 70)
  AddTextBar("주문타이머", "주문타이머 : ", "LEFT", "TOP", x + 0, -44, 70)
  AddTextBar("생존기", "생존기 : ", "LEFT", "TOP", x + 0, -56, 70)
  AddTextBar("디버프", "디버프 : ", "LEFT", "TOP", x + 0, -68, 70)
  AddTextBar("공대버프", "공대버프 : ", "LEFT", "TOP", x + 0, -80, 70)
end
function InvenRaidFrames3CPUUsage_Click()
	if not IRF3.disableLibAuras then
		IRF3.disableLibAuras = true
		DEFAULT_CHAT_FRAME:AddMessage("IRF Aura Library OFF", 1,1,1);
		if InvenRaidFrames3CPUUsage:IsShown() then
			InvenRaidFrames3CPUUsage.TextTitle["TITLE"]:SetText("LibAuras OFF")
		end
		LibStub("IRFLibAuras"):Stop()
	else
		IRF3.disableLibAuras = false
		DEFAULT_CHAT_FRAME:AddMessage("IRF Aura Library ON", 1,1,1);
		if InvenRaidFrames3CPUUsage:IsShown() then
			InvenRaidFrames3CPUUsage.TextTitle["TITLE"]:SetText("LibAuras ON")
		end
		LibStub("IRFLibAuras"):Start()
	end
end
function InvenRaidFrames3CPUUsage_Load()

	InvenRaidFrames3CPUUsage = CreateFrame("Button", "IRF_TEST", IRF3, "SecureHandlerClickTemplate")
	InvenRaidFrames3CPUUsage:SetFrameStrata("MEDIUM")
  InvenRaidFrames3CPUUsage:SetMovable(true)
  InvenRaidFrames3CPUUsage:SetClampedToScreen(true)
  InvenRaidFrames3CPUUsage:RegisterForClicks("AnyUp")
  
	InvenRaidFrames3CPUUsagePopup = CreateFrame("Button", "IRF_TEST2", IRF3, "SecureHandlerClickTemplate")
	InvenRaidFrames3CPUUsagePopup:SetFrameStrata("MEDIUM")
  InvenRaidFrames3CPUUsagePopup:SetMovable(true)
  InvenRaidFrames3CPUUsagePopup:SetWidth(10)
  InvenRaidFrames3CPUUsagePopup:SetHeight(10)
  InvenRaidFrames3CPUUsagePopup:SetClampedToScreen(true)
  InvenRaidFrames3CPUUsagePopup:RegisterForClicks("AnyUp")
  InvenRaidFrames3CPUUsagePopup:Hide()
  
  InitUI()
  
  InvenRaidFrames3CPUUsage:SetScript('OnClick', function(self, button, down)
    if button == "LeftButton" then
      ResetCPUUsage()
      afterCPU = 0
      InvenRaidFrames3CPUUsage_Click()
      setBackColor(InvenRaidFrames3CPUUsage, 1)
    elseif button =="RightButton" then
      InvenRaidFrames3CPUUsage:Hide()
      InvenRaidFrames3CPUUsagePopup:Show()
    end
  end)
  InvenRaidFrames3CPUUsagePopup:SetScript('OnClick', function(self, button, down)
    InvenRaidFrames3CPUUsage:Show()
    InvenRaidFrames3CPUUsagePopup:Hide()
  end)
  
  InvenRaidFrames3CPUUsage:SetScript('OnEnter', function()
    setBackColor(InvenRaidFrames3CPUUsage, 1)
  end)
  InvenRaidFrames3CPUUsage:SetScript('OnLeave', function()
    setBackColor(InvenRaidFrames3CPUUsage, 0)
  end)
  
	InvenRaidFrames3CPUUsage:SetScript("OnUpdate", function(self, elapsed)
		updateTimer = updateTimer + elapsed
    if updateTimer > updateFrequency then
      updateTimer = updateTimer - updateFrequency
      local framerate = GetFramerate();
      UpdateAddOnMemoryUsage()
      UpdateAddOnCPUUsage()
      local mem = GetAddOnMemoryUsage("InvenRaidFrames3") / 1000
      local cpu = GetAddOnCPUUsage("InvenRaidFrames3")
      InvenRaidFrames3CPUUsage.Text["MEM"]:SetText(formatNumber(mem,"%.1f\124cffffd200MB  FPS: ".. floor(framerate)))
      InvenRaidFrames3CPUUsage.Text["CPU"]:SetText(formatNumber((cpu - afterCPU),"%.2f \124cffffd200ms/s"))
      afterCPU = cpu
      
      SetItem("주문타이머", InvenRaidFrames3Member_UpdateSpellTimer)
      SetItem("생존기", InvenRaidFrames3Member_UpdateSurvivalSkill)
      SetItem("디버프", InvenRaidFrames3Member_UpdateAura)
      SetItem("공대버프", InvenRaidFrames3Member_UpdateBuffs)
    end
  end)
	
	setBackground(InvenRaidFrames3CPUUsage, InvenRaidFrames3, 80, 35, 52)
	setBorder(InvenRaidFrames3CPUUsage)
	setBackground(InvenRaidFrames3CPUUsagePopup, InvenRaidFrames3, 2, 80, 1)
	setBorder(InvenRaidFrames3CPUUsagePopup)
	InvenRaidFrames3CPUUsagePopup:SetScale(0.3)

end


function InvenRaidFrames3CPUUsage_Toggle()
	if InvenRaidFrames3CPUUsage then
		if InvenRaidFrames3CPUUsage:IsShown() then
			InvenRaidFrames3CPUUsage:Hide()
		else
			InvenRaidFrames3CPUUsage:Show()
		end
	else
		InvenRaidFrames3CPUUsage_Load()
	end
end