local Rx = require 'Rx'

local SingleAssignmentDisposable = Rx.SingleAssignmentDisposable

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

local schedulePeriodicRecursivePrototype = {

    _scheduler = false,

    _state = false,

    _period = false,

    _action = false,

    _cancel = false,

}

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

local function createTick(self)

    return function(command, recurseFn)

        recurseFn(0, self._period)

        local status, message = pcall(function()
            self._state = self._action(self._state)
        end)

        if not status then
            self._cancel:dispose()
            error(message)
        end

    end

end

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

function schedulePeriodicRecursivePrototype:__init(scheduler, state, period, action)

    self._scheduler = scheduler
    self._state = state
    self._period = period
    self._action = action

end

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

function schedulePeriodicRecursivePrototype:start()

    local d = SingleAssignmentDisposable()
    self._cancel = d

    d:setDisposable(
        self._scheduler:scheduleRecursiveFuture(0, self._period, createTick(self)))

    return d

end

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

return Rx.Class('Rx.internals.SchedulePeriodicRecursive', schedulePeriodicRecursivePrototype)
