local super = require "Control"

PositionPicker = super:new()

function PositionPicker:new()
    self = super.new(self)
    
    self.value = {x = 1, y = 1}
    
    return self
end

function PositionPicker:draw(canvas)
    local strokeThickness = 1 / canvas:metrics():backingScale()
    local rect = self:rect()
    canvas:setPaint(Color.gray(0.7))
        :fill(Path.rect(rect))
    canvas:setPaint(Color.white)
        :fill(Path.rect(rect:insetXY(strokeThickness, strokeThickness)))
    local selectedX, selectedY = self.value.x, self.value.y
    local width = rect:width()
    local height = rect:height()
    for iy = 0, 2 do
        local y = height/12 + height*5/6 * (iy + 0.5) / 3
        for ix = 0, 2 do
            local x = width/12 + width*5/6 * (ix + 0.5) / 3
            local paint
            if ix == selectedX and iy == selectedY then
                paint = Color.gray(0.3)
            else
                paint = Color.gray(0.7)
            end
            local radius = 2
            local dot = Path.oval{
                left = x - radius,
                bottom = y - radius,
                right = x + radius,
                top = y + radius,
            }
            canvas:setPaint(paint):fill(dot)
        end
    end
end

function PositionPicker:down(x, y)
    local rect = self:rect()
    local ix = math.min(math.max(0, math.floor(3 * (x - rect:minx()) / rect:width())), 2)
    local iy = math.min(math.max(0, math.floor(3 * (y - rect:miny()) / rect:height())), 2)
    self:setValue(ix, iy)
    self:action()
    return true
end

function PositionPicker:dragged(x, y)
    local rect = self:rect()
    local newX = math.min(math.max(0, math.floor(3 * (x - rect:minx()) / rect:width())), 2)
    local newY = math.min(math.max(0, math.floor(3 * (y - rect:miny()) / rect:height())), 2)
    local oldX, oldY = self:getValue()
    if newX ~= oldX or newY ~= oldY then
        self:setValue(newX, newY)
        self:action()
    end
end

function PositionPicker:up()
end

function PositionPicker:getValue()
    return self.value
end

function PositionPicker:setValue(x, y)
    self.value = {x = x, y = y}
    self:invalidate()
end

return PositionPicker
