local Rx = require 'Rx'

local ObservableBase = Rx.ObservableBase
local SchedulerArgument = Rx.internals.SchedulerArgument

local unpack = table.unpack or unpack

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

local JustObservable = Rx.Class 'Rx.internals.JustObservable' {

    ObservableBase,
        --superclass

    _value = false,
        -- (table with n = length)

    _scheduler = false,
        -- (Scheduler)

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

    __init = function(self, value, scheduler)
        self._value = value
        self._scheduler = scheduler
    end,

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

    subscribeCore = function(self, observer)

        local function scheduleItem(scheduler, value)

            observer:onNext(unpack(value, 1, value.n))

            observer:onCompleted()

        end

        return self._scheduler:schedule(self._value, scheduleItem)

    end,

}

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

return function(...)

    local lastArgIsScheduler, scheduler = SchedulerArgument.fromVarArgs(
        'Rx.Observable.just', 'immediate', ...)

    local numArgs = select('#', ...)
    if lastArgIsScheduler then
        numArgs = numArgs - 1
    end

    local value = { n = numArgs, ... }

    return JustObservable(value, scheduler)

end
