NUiTarget = {}

local sw, sh

function NUiTarget:SetupUI()
    require("nui-hud")
    self:ParseConfig("nui-hud.tbl")
end

function NUiTarget:ParseConfig(file)
    NUi:ParseGeneralSettings(file, self)
    NUi:ParseConfigSection(file, "#Target Bar Settings", function() self:ConfigTargetBar() end)
end

function NUiTarget:ConfigTargetBar()
    local sf = self.ScaleFactor

    if parse.optionalString("$Bar Height:") then
        self.BarH = parse.getFloat() * sf
    else
        self.BarH = 5 * sf
    end

    if parse.optionalString("$Bar Offset:") then
        self.BarOffset = parse.getFloat() * sf
    else
        self.BarOffset = 6 * sf
    end

    if parse.optionalString("$Min Bar Width:") then
        self.MinBarW = parse.getFloat() * sf
    else
        self.MinBarW = 40 * sf
    end

    if parse.optionalString("$Background Color:") then
        local c = NUi:GetCSV(parse.getString())
        self.BgColor = { tonumber(c[1]), tonumber(c[2]), tonumber(c[3]), tonumber(c[4]) or 180 }
    else
        self.BgColor = { 0, 0, 0, 180 }
    end

    if parse.optionalString("$Bar Color:") then
        local c = NUi:GetCSV(parse.getString())
        self.BarColor = { tonumber(c[1]), tonumber(c[2]), tonumber(c[3]), tonumber(c[4]) or 220 }
    else
        self.BarColor = { 255, 0, 0, 220 }
    end

    parse.requiredString("#End")
    self.Active = true
    NDebugger:log("NUiTarget", "ConfigTargetBar() complete.")
end

function NUiTarget.Setup()
    sw = gr.getScreenWidth()
    sh = gr.getScreenHeight()
end

function NUiTarget:Draw()
    if not self.Active then return end

    local plyr = hv.Player
    if not plyr or not plyr:isValid() then return end

    local target = plyr.Target
    if not target or not target:isValid() then return end
    if target:getBreedName() ~= "Ship" then return end

    if BossBar and BossBar.Boss and BossBar.Boss:isValid()
        and target:getSignature() == BossBar.Boss:getSignature() then return end

    local hpMax = target.HitpointsMax
    if not hpMax or hpMax <= 0 then return end

    local ratio = math.max(0, math.min(1, target.HitpointsLeft / hpMax))

    local x1, y1, x2, y2 = gr.drawTargetingBrackets(target, false)
    if not x1 or not y2 then return end

    if x2 <= 0 or x1 >= sw or y2 <= 0 or y1 >= sh then return end

    local barW = math.max(x2 - x1, self.MinBarW)
    local barX = x1 + (x2 - x1) / 2 - barW / 2
    local barY = y2 + self.BarOffset
    local barH = self.BarH

    local bg = self.BgColor
    gr.setColor(bg[1], bg[2], bg[3], bg[4])
    gr.drawRectangle(barX, barY, barX + barW, barY + barH, true)

    local c = self.BarColor
    gr.setColor(c[1], c[2], c[3], c[4])
    gr.drawRectangle(barX, barY, barX + barW * ratio, barY + barH, true)
end
