local super = require "DataPresenter"

FilterDataPresenter = super:new()

FilterDataPresenter.conjunctionCombinationRule = 'all'
FilterDataPresenter.disjunctionCombinationRule = 'any'

local defaults = {
    match = FilterDataPresenter.conjunctionCombinationRule,
}

local nilDefaults = {
}

function FilterDataPresenter: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
    
    return self
end

function FilterDataPresenter:ruleClass()
    return FilterRule
end

function FilterDataPresenter:apply(dataset)
    if self._rules:count() > 0 then
        Profiler.time('FilterDataPresenter:apply', function()
            local sequence = dataset:entrySequence()
            sequence = sequence:filter(self:getRuleSequence(dataset)):compact()
            dataset = self:rewrap(sequence)
        end)
    end
    return dataset
end

function FilterDataPresenter:getRuleSequence(dataset)
    local sequence
    local sequences = {}
    for rule in self._rules:iter() do
        sequences[#sequences + 1] = rule:evaluate(dataset)
    end
    if self:getCombinationRule() == FilterDataPresenter.conjunctionCombinationRule then
        sequence = LogicLibrary.conjunction(unpack(sequences))
    else
        sequence = LogicLibrary.disjunction(unpack(sequences))
    end
    return sequence
end

function FilterDataPresenter:getCombinationRule()
    return self:getProperty('match')
end

return FilterDataPresenter
