local Rx = require 'Rx'

local Scheduler = Rx.Scheduler

--------------------------------------------------------------------------------

local SchedulerArgument = {}

--------------------------------------------------------------------------------

function SchedulerArgument.validateWithDefault(methodName, defaultName, scheduler)

    if not scheduler then
        scheduler = Rx.config.defaultScheduler
    end

    if scheduler then
        if not Scheduler:isClassOf(scheduler) then
            error(methodName .. ": scheduler, if provided, must be a Scheduler object", 3)
        end
    else
        scheduler = Scheduler[defaultName]()
    end

    return scheduler

end

--------------------------------------------------------------------------------

function SchedulerArgument.validateWithoutDefault(methodName, scheduler)

    if not scheduler then
        scheduler = Rx.config.defaultScheduler
    end

    if scheduler then
        if not Scheduler:isClassOf(scheduler) then
            error(methodName .. ": scheduler must be a Scheduler object", 3)
        end
    else
        error(methodName .. ": scheduler argument is not optional", 3)
    end

    return scheduler

end

--------------------------------------------------------------------------------

function SchedulerArgument.fromVarArgs(methodName, defaultName, ...)

    local values = { ... }
    local nValues = select('#', ...)

    local lastArg = values[nValues]

    if Scheduler:isClassOf(lastArg) then
        return true, lastArg
    else
        local scheduler = Rx.config.defaultScheduler
        if not scheduler then
            scheduler = Scheduler[defaultName]()
        end
        if not Scheduler:isClassOf(scheduler) then
           error(methodName .. ": Rx.config.defaultScheduler is invalid", 3)
        end
        return false, scheduler
    end

end

--------------------------------------------------------------------------------

return SchedulerArgument
