local super = require "DataPresenter"

SortDataPresenter = super:new()

SortDataPresenter.ascendingDirection = "ascending"
SortDataPresenter.descendingDirection = "descending"

function SortDataPresenter:ruleClass()
    return SortRule
end

function SortDataPresenter:apply(dataset)
    if self._rules:count() > 0 then
        Profiler.time('SortDataPresenter:apply', function()
            local sequence = dataset:entrySequence()
            local rule = self._rules:get(1)
            if rule then
                local isDescending = (rule:getDirection() == SortDataPresenter.descendingDirection)
                local isIndex = rule:getArtifact():isa(IndexArtifact)
                if isIndex then
                    if isDescending then
                        sequence = sequence:reverse()
                    end
                else
                    sequence = sequence:sort(rule:evaluate(dataset), isDescending)
                end
            end
            dataset = self:rewrap(sequence)
        end)
    end
    return dataset
end

function SortDataPresenter:hasRules()
    if super.hasRules(self) then
        local rule = self._rules:get(1)
        if rule then
            local isDescending = (rule:getDirection() == SortDataPresenter.descendingDirection)
            local isIndex = rule:getArtifact():isa(IndexArtifact)
            return isDescending or not isIndex
        end
    end
    return false
end

return SortDataPresenter
