local ComplexHPBar = Object:extend()

local gui         = require "game.modules.gui"

local VALUE_MARGIN = 11
local HEIGHT = 7

function ComplexHPBar:new(width)
    self.width = width
    self:setColorForeground(1, 1, 1)
    self:setColorBackground(0, 0, 0)
    self.background = self:createBack( "assets/gui/hpbar_back.png" )
    self.foreground = self:createBack( "assets/gui/hpbar_fore.png" )
end

function ComplexHPBar:setColorForeground(r, g, b)
    self.barcolor = {}
    self.barcolor.r = r
    self.barcolor.g = g
    self.barcolor.b = b
end

function ComplexHPBar:setColorBackground(r, g, b)
    self.backcolor = {}
    self.backcolor.r = r
    self.backcolor.g = g
    self.backcolor.b = b
end

function ComplexHPBar:createBack( filepath )
    local image = love.graphics.newImage( filepath )
    local imageWidth, imageHeight = image:getDimensions()
    local middleImageWidth = imageWidth - VALUE_MARGIN*2

    local totalWidth = self.width + 8 -- On récupère la taille à partir de la base
    local middleWidth = totalWidth - VALUE_MARGIN*2

    local iteration = math.ceil((middleWidth) / (middleImageWidth))
    local tilequad  = {}
    tilequad[1]     = love.graphics.newQuad(0, 0, VALUE_MARGIN, imageHeight, imageWidth, imageHeight)
    tilequad[2]     = love.graphics.newQuad(VALUE_MARGIN, 0, middleImageWidth, imageHeight, imageWidth, imageHeight)
    tilequad[3]     = love.graphics.newQuad(imageWidth - VALUE_MARGIN, 0, VALUE_MARGIN, imageHeight, imageWidth, imageHeight)

    local canvas1 = love.graphics.newCanvas(middleWidth, imageHeight)
    love.graphics.setCanvas( canvas1 )
    local combinedWidth = 0
    for i = 1, iteration do
        love.graphics.draw(image, tilequad[2], combinedWidth, 0)
        combinedWidth = combinedWidth + middleImageWidth
    end

    local canvas2 = love.graphics.newCanvas(totalWidth, imageHeight)
    love.graphics.setCanvas( canvas2 )
    love.graphics.draw(image, tilequad[1], 0, 0)
    love.graphics.draw(canvas1, VALUE_MARGIN, 0)
    love.graphics.draw(image, tilequad[3], totalWidth - 11, 0)
    love.graphics.setCanvas( )

    local imagedata = canvas2:newImageData()
    local texture   = love.graphics.newImage( imagedata )
    imagedata:release()
    canvas2:release()

    return texture
end

function ComplexHPBar:draw(x, y, percent)
    utils.graphics.resetColor()
    love.graphics.draw(self.foreground, x, y)
    love.graphics.setColor(self.backcolor.r, self.backcolor.g, self.backcolor.b, 1)
    love.graphics.draw(self.background, x, y)
    utils.graphics.resetColor()

    love.graphics.setColor(self.barcolor.r, self.barcolor.g, self.barcolor.b, 1)
    gui.drawBar(x + 4, y + 2, math.floor((self.width) * percent), HEIGHT)
    utils.graphics.resetColor()
end

function ComplexHPBar:drawWithLabels(x, y, value, valuemax)
    local percent = value / valuemax
    self:draw(x, y, percent)
    love.graphics.print(math.floor(value) .. "/" .. valuemax, x+10, y+2)
end

return ComplexHPBar
