local super = require "TableColumn"

ArrowColumn = super:new()

local defaults = {
    min = 0,
    max = 100,
}

local nilDefaults = {
    'value', 'value2', 'paint',
}

local getterNames = {'min', 'max', 'value', 'value2', 'paint'}

local inspectorInfo = {
    {'KeyArtifact', {'value'}, 'Start'},
    {'KeyArtifact', {'value2'}, 'End'},
    {'Range', {min = 'min', max = 'max'}, 'Range'},
    {'Color', {'getPaint:setPaint', custom = 'hasExplicitPaint:'}, 'Color'},
}

function ArrowColumn:new()
    self = super.new(self)
    
    for k, v in pairs(defaults) do
        self:addProperty(k, v)
    end
    for _, k in pairs(nilDefaults) do
        self:addProperty(k)
    end
    
    self.stamp = HorizontalArrowStamp
    self.getterNames = getterNames
    self.inspectorInfo = inspectorInfo
    
    return self
end

function ArrowColumn:unarchived()
    local dataset = self:getDataset()
    if dataset then
        if self:getProperty('value') == nil and self:getProperty('value2') == nil then
            local field1 = dataset:pickField('number')
            if field1 then
                local field2 = dataset:pickField('number', { field1 })
                if field2 then
                    self:setProperty('value', KeyArtifact:new(field1))
                    self:setProperty('value2', KeyArtifact:new(field2))
                    self:setTitle(field1 .. '–' .. field2)
                end
            end
        end
    end
    super.unarchived(self)
end

function ArrowColumn:drawCell(canvas, rect, rangeMin, rangeMax, value1, value2, paint)
    rect = rect:insetXY(0, rect:height() / 6)
    local parent = self:getParent()
    canvas:setPaint(parent:getEmptyFillPaint())
        :fill(Path.rect(rect))
    value1, value2 = tonumber(value1), tonumber(value2)
    if value1 and value2 then
        local y = rect:midy()
        local x1 = rect:mapPointX((value1 - rangeMin) / (rangeMax - rangeMin))
        local x2 = rect:mapPointX((value2 - rangeMin) / (rangeMax - rangeMin))
        HorizontalArrowStamp(canvas, y, x1, x2, rect:height() * 0.4, paint or parent:getAccentPaint())
    end
end

function ArrowColumn:getDefaultPaint()
    return self:getParent():getAccentPaint()
end

return ArrowColumn
