local _, addonTable = ...
local config = addonTable.getConfig()

local EnergyBar = CreateFrame("Frame", "EnergyBar", UIParent, "BackdropTemplate")

function EnergyBar:createEnergyBar()
    if self.Border or self.TextFrame or self.TextValue or self.StatusBar then return end

    self.Border = self:CreateTexture(nil, "OVERLAY")
    self.Border:SetTexture("Interface\\BUTTONS\\WHITE8X8")
    self.Border:SetVertexColor(0, 0, 0, 0.5)

    self.TextFrame = CreateFrame("Frame", nil, self)

    self.TextValue = self.TextFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    self.TextValue:SetJustifyH("CENTER")
    self.TextValue:SetFont("Fonts\\FRIZQT__.TTF", 21, "OUTLINE")

    self.StatusBar = CreateFrame("StatusBar", nil, self)
    self.StatusBar:SetStatusBarTexture("Interface\\TARGETINGFRAME\\UI-StatusBar")

    self:updateLayout()

    local elapsed = 0
    EnergyBar:SetScript("OnUpdate", function(self, delta)
        elapsed = elapsed + delta
        if elapsed > 0.01 then
            self:updateEnergy()
            elapsed = 0
        end
    end)
end
function EnergyBar:destroyEnergyBar()
    if self.Border then
        self.Border:Hide()
        self.Border = nil
    end
    if self.TextFrame then
        self.TextFrame:Hide()
        self.TextFrame = nil
    end
    if self.TextValue then
        self.TextValue:Hide()
        self.TextValue = nil
    end
    if self.StatusBar then
        self.StatusBar:Hide()
        self.StatusBar = nil
    end
    EnergyBar:SetScript("OnUpdate", nil);
end

function EnergyBar:updateLayout()
    local config = addonTable.getConfig()
    self:SetSize((5*config.scale*64 + 3*config.gap)*0.9, 18)
    self:SetPoint("BOTTOM", 'ScritchPopComboPoints', "TOP", 0, 10)  

    self.Border:SetPoint("TOPLEFT", -2, 2)
    self.Border:SetPoint("BOTTOMRIGHT", 2, -2)

    self.TextFrame:SetAllPoints()

    self.TextValue:SetPoint("CENTER", self.TextFrame, "CENTER", 0, 0)

    self.StatusBar:SetAllPoints()
    self.StatusBar:SetStatusBarTexture("Interface\\TARGETINGFRAME\\UI-StatusBar")
    self.StatusBar:SetStatusBarColor(1, 1, 0)   
end

function EnergyBar:updateEnergy()
    if not self.StatusBar then
        self:createEnergyBar()
    end

    local energy = UnitPower("player", Enum.PowerType.Energy)
    local max_energy = UnitPowerMax("player", Enum.PowerType.Energy)

    self.StatusBar:SetMinMaxValues(0, max_energy)
    self.StatusBar:SetValue(energy)
    self.TextValue:SetText(energy)
end

addonTable.EnergyBar = EnergyBar