local Rx = require 'Rx'

local Disposable = Rx.Disposable

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

local serialDisposablePrototype = {

    Disposable,
        -- superclass

    _current = false,
        -- (Disposable) current item to dispose
}

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

function serialDisposablePrototype:__init(disposable)

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

    self._current = disposable

    return function()

        if self._current then
            local old = self._current
            self._current = nil
            old:dispose()
        end

    end

end

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

function serialDisposablePrototype:getDisposable()

    return self._current

end

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

function serialDisposablePrototype:setDisposable(disposable)

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

    local shouldDispose = self:isDisposed()
    local old

    if not shouldDispose then
        old = self._current
        self._current = disposable
    end

    if old then
        old:dispose()
    end

    if shouldDispose and disposable then
        disposable:dispose()
    end

end

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

return Rx.Class('Rx.SerialDisposable', serialDisposablePrototype)
