local super = require "Button"

HalfButton = super:new()

function HalfButton:new()
    self = super.new(self)
    
    self.icon = nil
    self.paint = nil
    
    return self
end

function HalfButton:buttonRect()
    return self:rect():inset{left = 13, right = 1, bottom = 1, top = 1}
end

function HalfButton:draw(canvas)
    local rect = self:rect()
    local fillPath = Path.rect(rect:insetXY(self:fillInset(), self:fillInset()), 3)
    local shadowPath = Path.rect(rect:insetXY(self:fillInset() + self:shadowInset() / 2, self:fillInset() + self:shadowInset()), 3 - self:shadowInset() / 2)
    local strokePath = Path.rect(rect:insetXY(0.5, 0.5), 2.5)
    
    -- draw shadow
    canvas:preserve(function(canvas)
        canvas:concatTransformation(Transformation.identity():translate(0, -self:shadowOffset()))
            :setPaint(self:shadowPaint())
            :fill(shadowPath)
    end)
    
    -- draw background
    canvas:setPaint(self:fillPaint(rect))
        :fill(fillPath)
    
    -- draw outline
    canvas:setPaint(self:strokePaint())
        :setThickness(1)
        :stroke(strokePath)
    
    -- draw icon
    local icon = self.icon
    if icon then
        local buttonRect = self:buttonRect()
        local iconRect = Rect:new(icon:canvas():metrics():rect())
        local hInset = math.max(2, buttonRect:width() - iconRect:width()) / 2
        local vInset = math.max(2, buttonRect:height() - iconRect:height()) / 2
        local drawIconRect = buttonRect:insetXY(hInset, vInset):offset(-2, 0)
        canvas:preserve(function(canvas)
            canvas:clipIcon(icon, drawIconRect:offset(0, -0.75))
                :setPaint(Color.gray(0, 0.25))
                :fill(Path.rect(buttonRect))
        end)
        canvas:preserve(function(canvas)
            canvas:clipIcon(icon, drawIconRect)
                :setPaint(self.paint or Color.gray(0.4))
                :fill(Path.rect(buttonRect))
        end)
        if self:getStatus() then
            canvas:preserve(function(canvas)
                canvas:clipIcon(icon, drawIconRect)
                    :setPaint(self:tintPaint())
                    :fill(Path.rect(buttonRect))
            end)
        end
    end
end

function HalfButton:fillPaint(rect)
    if self:getStatus() then
        return Color.gray(0.95)
    else
        return Color.gray(0.99)
    end
end

function HalfButton:fillInset()
    return 1
end

function HalfButton:strokePaint()
    return Color.invisible
end

function HalfButton:shadowPaint()
    if self:isActive() then
        return Color.gray(0, 0.2)
    else
        return Color.gray(0, 0.1)
    end
end

function HalfButton:shadowInset()
    return -0.5
end

function HalfButton:shadowOffset()
    return 0.25
end

function HalfButton:tintPaint()
    return Color.gray(0, 0.1)
end

function HalfButton:setIcon(icon)
    self.icon = icon
    self:invalidate()
end

function HalfButton:setPaint(paint)
    self.paint = paint
    self:invalidate()
end

return HalfButton
