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

WFCatTaskManager.lua

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

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

NOTICE: All information contained herein is, and remains 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 are protected by all applicable
intellectual property laws, including trade secret and copyright laws.
Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

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

local Rx = require 'Rx'

local WFLogger = require 'WFLogger'
local WFRxRunUntilDone = require 'WFRxRunUntilDone'
local WFRequestQueue = require 'WFRequestQueue'
local WFArguments = require 'WFArguments'

local Observable = Rx.Observable
local Disposable = Rx.Disposable

local logger = WFLogger( "WFCatTaskManger" )

--==============================================================================

local _gCatTaskManager = nil

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

local WFCatTaskManager = {
	
	Disposable,
	
	_taskQueue = false,
	
	_processorStream = false,
	
	_runLoopTask = false,
	
	_inProgress = false,
	
	_processingTask = false,
	
}

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

local function taskProcessor( self )

	return self._processorStream
	
		:filter( function()
			return not self._inProgress
		end )
		
		:flatMapLatest( function( value )
			self._inProgress = true
			
			local resultStream
			local task = self:nextTask()
			
			self._processingTask = task
			
			if task and not task:cancelled() then
				resultStream = task:performAction()
			end

			return resultStream or Observable.just( true )
		end )
		
		:flatMapLatest( function( result )
			if self._processingTask then
				self._processingTask:close()
				self._processingTask = nil
			end
			
			self._inProgress = false
			
			return self._taskQueue:size()
		end )
		
		:map( function( pendingTaskSize )
			-- handle next pending task
			if pendingTaskSize > 0 then
				self._processorStream:onNext( true )
			end
		end )

		:catch( function( errorMessage )
			self._inProgress = false
			
			logger:errorf( "WFCatTaskManager report error : %s", errorMessage )
			
			return self._runLoopTask:throwIfNotStopped( errorMessage )
		end )
		
		:finally( function()
			logger:info( "WFCatTaskManager taskProcessor completed" )
		end )
		
		:call( WFRxRunUntilDone )

end

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

function WFCatTaskManager:__init()
	
	self._processorStream = Rx.ReplaySubject( 1 )
	
	self._taskQueue = WFRequestQueue()
	
	self._inProgress = false
	
end

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

function WFCatTaskManager:start()
	self._runLoopTask = taskProcessor( self )
end

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

function WFCatTaskManager:close()
	if self._processingTask then
		self._processingTask:cancelTask()
	end

	if self._processorStream then
		self._processorStream:dispose()
		self._processorStream = nil
	end
	
	if self._runLoopTask then
		self._runLoopTask:dispose()
		self._runLoopTask = nil
	end
end

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

function WFCatTaskManager:addToQueue( task )
	self._taskQueue:addToQueue( task )
	self._processorStream:onNext( true )
	
	return task
end

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

function WFCatTaskManager:nextTask()
	return self._taskQueue:nextRequest()
end

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

local WFCatTaskManagerInstance = Rx.Class 'WFCatTaskManager'( WFCatTaskManager )

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

local function getCatTaskManager( wfCatalog )
	
	WFArguments.check( 'WFCatalog' )

	if not _gCatTaskManager then
		_gCatTaskManager = WFCatTaskManagerInstance()
		
		_gCatTaskManager:start()
				
		wfCatalog:addCloseAction( function()
		   _gCatTaskManager:close()
		   _gCatTaskManager = nil
		end )
	end
	
	return _gCatTaskManager
end

--==============================================================================

return {

	getCatTaskManager = getCatTaskManager,
	
}
