local super = require "Artifact"

LogicArtifact = super:new()

function LogicArtifact:new(input, ...)
    self = super.new(self)
    
    if type(input) == 'string' then
        self:trySetValue(input, warn)
    else
        self:setValue(input, ...)
    end
    self:setUndoable(true)
    
    return self
end

function LogicArtifact:archive()
    local typeName, properties = self:class(), {
        logic = self:getInput()
    }
    return typeName, properties
end

function LogicArtifact:trySetValue(input, errorFunction)
    local parsedLogic = ParsedLogic:new(input)
    local parsedFunction, parsedDependencies = parsedLogic:getFunction(), parsedLogic:getDependencies()
    if parsedFunction or not self._input then
        return self:setValue(parsedLogic, parsedDependencies, parsedFunction and function(dataset)
            return ezpcall(function() return parsedFunction(dataset) end)
        end)
    end
    if not parsedFunction then
        errorFunction(parsedLogic:getError())
    end
end

function LogicArtifact:unarchiveLogic(archived)
    self:trySetValue(unarchive(archived), warn)
end

return LogicArtifact
