local Rx = require 'Rx'

local Disposable = Rx.Disposable

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

local innerSubscriptionPrototype = {

    Disposable,
        -- superclass

    _subject = false,
        -- (Subject)

    _observer = false,
        -- (Observer)

}

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

local function findObserver(observers, observer)

    for i, next in ipairs(observers) do

        if next == observer then
            return i
        end

    end

end

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

function innerSubscriptionPrototype:__init(subject, observer)

    self._subject = subject
    self._observer = observer

    return function()

        if self._subject and not self._subject:isDisposed() and self._observer ~= nil then

            local index = findObserver(self._subject._observers, self._observer)

            if index then

                table.remove(self._subject._observers, index)

                if self._subject._ohoObservers and #self._subject._observers == 0 then
                    for _, ohoObserver in ipairs(self._subject._ohoObservers) do
                        ohoObserver:onNext(false)
                    end
                end

                self._observer = nil
                self._subject = nil

            end

        end

    end

end

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

return Rx.Class('Rx.internals.InnerSubscription', innerSubscriptionPrototype)
