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

WFRxNativeObservable.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.

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

	-- RxLua
local Rx = require 'Rx'
local Disposable = Rx.Disposable
local Observable = Rx.Observable

	-- WF.core.util
local WFArguments = require 'WFArguments'
local WFLogger = require 'WFLogger'

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

local logger = WFLogger( 'WFRxNativeObservable' )

local alreadyDisposedLogger = WFLogger( "AlreadyDisposedWFRxNativeObservable" )
	-- use a distinct name to log these issues, set the logLevel to info to enable.
	
--============================================================================--

-- @mark WFRxNativeObservable class

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

local WFRxNativeObservable = {

	Observable,

	_nativeObservableImp = false,
		-- (WFRxNativeObservableImp)

	_observer = false,
		-- (Rx.Observer)

	_nativeFunc = false,
		-- (function)

	_objInitStackTrace = false,
		-- (string)

	_args = false,
		-- (table)

	_didStart = false,
		-- (boolean) true if we got a subscriber (and thus started)

}

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

function WFRxNativeObservable:__init( nativeFunc, ... )

	WFArguments.check( 'WFRxNativeObservable', 'function' )

	self._objInitStackTrace = alreadyDisposedLogger.will_info and debug.traceback() or nil
		-- Set the logLevel to info to enable.
		
	self._nativeFunc = nativeFunc
	self._args = { n = select( '#', ... ), ... }

end

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

function WFRxNativeObservable:_subscribe( observer )

	local function severLinks()

		local nativeObservableImp = self._nativeObservableImp

		if nativeObservableImp then
			nativeObservableImp:close()
			nativeObservableImp = nil
		end

		self._nativeObservableImp = nil
		self._observer = nil

	end

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

	local function observableCallback( status, ... )

		local success, message = pcall( function( ...)

			local observer = self._observer

			if not observer then
				
				local origin = self._objInitStackTrace or "set logger AlreadyDisposedWFRxNativeObservable = 'info' in config.lua to enable"
				logger:debugf( "Observer already disposed. Was instantiated at: %s", origin )
				return

			end

			if status == 'data' then

				observer:onNext( ... )

			elseif status == 'error' then

				observer:onError( ... )
				severLinks()

			elseif status == 'done' then

				observer:onCompleted()
				severLinks()

			else

				logger:warnf( "Warning: Unknown message %s from native observable implementation", tostring( status ) )

			end

		end, ... )

		if not success then
			logger:errorf( "Uncaught error when processing native observable message: %s", message )
		end

	end

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

	if self._didStart then
		error( "WFRxNativeObservable: Can only subscribe once to a native observable", 2 )
	end

	self._didStart = true

	local args = self._args

	local nativeObservableImp = self._nativeFunc( observableCallback,
									  unpack( args, 1, args.n ) )

	if type( nativeObservableImp ) ~= 'userdata' then
		error( "WFRxNativeObservable: Native function did not return a suitable object", 2 )
	end

	self._nativeObservableImp = nativeObservableImp
	self._observer = observer

	return Disposable.create( severLinks )

end

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

return Rx.Class( 'WFRxNativeObservable', WFRxNativeObservable )
