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

WFCatDoOnce.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2016 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 Observable = Rx.Observable

	-- WF.core.utils
local WFArguments = require 'WFArguments'
local WFRxScheduler = require 'WFRxScheduler'
local WFRxRunUntilDone = require 'WFRxRunUntilDone'

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

local check = assert( WFArguments.check )

local runUntilDone = WFRxRunUntilDone

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

local doOnceDocId = 'WFCatDoOnce'
	
--------------------------------------------------------------------------------

return function( docStore, key, func, optArgs )

	check( 'WFRxDocStore', 'string', 'function', '?table' )

	optArgs = optArgs or {}

	local delay = optArgs.delay or 10

	-- This delay is keep the this work from contributing to app startup time.

	return Observable.timer( delay, WFRxScheduler.sharedScheduler() )

		:take( 1 )

		:flatMapLatest( function()

			return docStore:localDocValue( doOnceDocId )
			
				:flatMapLatest( function( docValue )
				
					local doOnceKeys = docValue.keys or {}
				
					if not doOnceKeys[ key ] or optArgs.forceFunctionRun then
					
						return func()
							:map( function()
								return doOnceKeys
							end )
							
					end
					
					return Observable.just( doOnceKeys )

				end )
				
				:flatMapLatest( function( doOnceKeys )
				
					doOnceKeys[ key ] = true

					return docStore:setLocalDocValue {
						_id = doOnceDocId,
						keys = doOnceKeys,
					}
				
				end )
				
			end )
				
		:takeLast( 0 )
				
		:call( runUntilDone )

end
