local super = require "Button"

ColorButton = super:new()

function ColorButton:new()
    self = super.new(self)
    
    self.color = Color.black
    
    return self
end

function ColorButton:draw(canvas)
    local strokeThickness = 1 / canvas:metrics():backingScale()
    local matteThickness = 2
    local rect = self:rect()
    local color = self:getColor()
    local outlinePath = Path.rect(rect, 3)
    local matteClipPath = Path.rect(rect:insetXY(strokeThickness, strokeThickness), 3 - strokeThickness)
    local colorRect = rect:insetXY(matteThickness, matteThickness)
    local colorPath = Path.rect(colorRect)
    
    -- draw outline
    canvas:setThickness(1)
        :setPaint(Color.gray(0, 0.3))
        :fill(outlinePath)
    
    -- draw color
    local triangle = Path.point{x = colorRect.right, y = colorRect.top}
    triangle:addLine{x = colorRect.right, y = colorRect.bottom}
    triangle:addLine{x = colorRect.left, y = colorRect.bottom}
    triangle:closeSubpath()
    canvas
        :setPaint(Color.black)
        :fill(colorPath)
        :setPaint(Color.white)
        :fill(triangle)
        :setPaint(color)
        :fill(colorPath)
    
    -- draw matte
    canvas:preserve(function(canvas)
        canvas:clip(matteClipPath)
            :setThickness(2 * matteThickness)
            :setPaint(self:getMattePaint())
            :stroke(Path.rect(rect, 3 + 0.5 * matteThickness))
    end)
end

function ColorButton:getMattePaint()
    if self:getStatus() then
        return Color.gray(0.9)
    else
        return Color.white
    end
end

function ColorButton:getColor()
    return self.color
end

function ColorButton:setColor(color)
    self.color = color
    self:invalidate()
end

return ColorButton
