local Rx = require 'Rx'

local Disposable = Rx.Disposable
local Scheduler = Rx.Scheduler

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

local scheduledDisposablePrototype = {

    Disposable,
        -- superclass

    _scheduler = false,
        -- (Scheduler)

    _disposable = false,
        -- (Disposable)

}

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

function scheduledDisposablePrototype:__init(scheduler, disposable)

    if not Disposable:isClassOf(disposable) then
        error(string.format("Rx.ScheduledDisposable: item (%s) is not a Disposable",
                tostring(disposable)), 2)
    end

    if not Scheduler:isClassOf(scheduler) then
        error(string.format("Rx.ScheduledDisposable: item (%s) is not a Scheduler",
                tostring(disposable)), 2)
    end

    self._scheduler = scheduler
    self._disposable = disposable

    return function()

        self._scheduler:schedule(function()

            local disp = self._disposable

            if not disp:isDisposed() then

                self._disposable = nil
                disp:dispose()

            end

        end)

    end

end

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

return Rx.Class('Rx.ScheduledDisposable', scheduledDisposablePrototype)
