local Rx = require 'Rx'

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

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

local function loopRecursive(start, count, observer)

    return function(i, recurseFn)

        if i < count then

            observer:onNext(start + i)

            recurseFn(i + 1)

        else

            observer:onCompleted()

        end

    end

end

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

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

    ObservableBase,
        -- superclass

    _start = false,
        -- (number)

    _count = false,
        -- (number)

    _scheduler = false,
        -- (Scheduler)

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

    __init = function(self, start, count, scheduler)

        self._start = start
        self._count = count
        self._scheduler = scheduler

    end,

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

    subscribeCore = function(self, observer)

        return self._scheduler:scheduleRecursive(0,
            loopRecursive(self._start, self._count, observer))

    end,

}

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

return function(start, count, scheduler)

    if type(start) ~= 'number' then
        error("Rx.Observable.range: start argument must be a number", 2)
    end

    if type(count) ~= 'number' then
        error("Rx.Observable.range: count argument must be a number", 2)
    end

    scheduler = SchedulerArgument.validateWithDefault('Rx.Observable.range',
                                                      'currentThread', scheduler)

    return RangeObservable(start, count, scheduler)

end
