--[[----------------------------------------------------------------------------

WFRxRunUntilDone.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2015 Adobe Systems Incorporated
All Rights Reserved.

NOTICE: All information contained herein is, and remain the property of
Adobe Systems Incorporated and its suppliers, if any. The intellectual and
technical concepts contained herein are proprietary to Adobe Systems
Incorporated and its suppliers and may be covered by U.S. and Foreign
Patents, patents in process, and are protected by trade secret or copyright
law.  Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

------------------------------------------------------------------------------]]

	-- WF.core.diagnostic_log
local WFDiagnosticLog = require 'WFDiagnosticLog'

local DEBUG = _G.DEBUG

local DEBUG_RUNUNTILDONE

local globalRunUntilDoneSubscriptions
local globalRunUntilDoneTracebacks

if globalRunUntilDoneSubscriptions == nil then

	globalRunUntilDoneSubscriptions = {}

	local WFConfiguration = require 'WFConfiguration'

	DEBUG_RUNUNTILDONE = DEBUG or WFConfiguration.Debug.debugRunUntilDone

	if DEBUG_RUNUNTILDONE then
		globalRunUntilDoneTracebacks = {}
	end

	WFDiagnosticLog.addLogSectionFunc( function()

		local numActiveSubscriptions = 0
		for k, v in pairs( globalRunUntilDoneSubscriptions ) do
			numActiveSubscriptions = numActiveSubscriptions + 1
		end

		local ok, maybeThreadName = pcall( function()
			return require 'WFCurrentThread'.DEBUG_getThreadName()
		end )

		local threadName = ok and maybeThreadName or
			"Unknown thread " .. tostring( math.random() )

		local subscriptions

		if DEBUG_RUNUNTILDONE and numActiveSubscriptions > 0 then

			local summary = {}

			for _, traceback in pairs( globalRunUntilDoneTracebacks ) do
				local subscriptionSummary = summary[ traceback ] or { count = 0, traceback = traceback }
				subscriptionSummary.count = subscriptionSummary.count + 1
				summary[ traceback ] = subscriptionSummary
			end

			subscriptions = {}
			for _, v in pairs( summary ) do
				table.insert( subscriptions, v )
			end

		end

		if numActiveSubscriptions > 0 then

			return {
				name = "WFRxRunUntilDone :: " .. threadName,
				id = 'WFRxRunUntilDone-' .. threadName:replace( ' :: ', '+' ),
				weight = 500,
				body = {
					numActiveSubscriptions = numActiveSubscriptions,
					subscriptions = subscriptions,
				},
			}
		
		else
		
			return {}
			
		end

	end )

end

--------------------------------------------------------------------------------
--[[!
	\brief Return an Observable that will run through to completion, regardless
		of whether anyone subscribes to it or not.
]]--

return function( self )

	local replayObservable = self:replay( nil, 1 )
		-- Use :replay() here because we need to add our own subscription (see
		-- just below) but need to not duplicate work if the caller to runUntilDone
		-- also subscribes. (See http://reactivex.io/documentation/operators/replay.html
		-- for a deeper discussion of the replay operator.)

	local function selfIsDone()
	
		local subscription = globalRunUntilDoneSubscriptions[ self ]
		globalRunUntilDoneSubscriptions[ self ] = nil
		
		if subscription then
			subscription:dispose()
		end
		
	end

	if DEBUG_RUNUNTILDONE then

		-- Use traceback 2 instead of 3 as syntax can also be WFRxRunUntilDone( observable )
		-- in addition to Observable:call( WFRxRunUntilDone ).
		globalRunUntilDoneTracebacks[ self ] = debug.traceback( '', 2 )

		local prevSelfIsDone = selfIsDone
		selfIsDone = function()
			prevSelfIsDone()
			globalRunUntilDoneTracebacks[ self ] = nil
		end

	end

	local runUntilDoneSubscription = replayObservable:subscribe( nil, selfIsDone, selfIsDone )
		-- In addition to onCompleted, subscribe to onError to override the
		-- default behavior of throwing an error via error as replay will
		-- forward the error.

	globalRunUntilDoneSubscriptions[ self ] = runUntilDoneSubscription

	replayObservable:connect()

	return replayObservable

end
