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

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.reactive
local KSReactive = require 'KSReactive'
local Rx = require 'Rx'

	-- WF.core.lua
local _ = require 'WFRequestDispatcher'

	-- WF.core.utils
local WFUnknown = require 'WFUnknown'
local WFModelsUtils = require 'WFModelsUtils'
local WFCloseSupport = require "WFCloseSupport"
local WFArguments = require "WFArguments"

local WFCatTestSession = require "WFCatTestSession"
local WFTableMerge = require "WFTableMerge"

	-- WF.lrmobile_models
local LrmCatalogTestHelper = require 'LrmCatalogTestHelper'
local LrmLibraryModelFactory = require 'LrmLibraryModelFactory'

local LrmOzPurgeAgent = require "LrmOzPurgeAgent"
local LrmSyncManager = require "LrmSyncManager"

local WFRxRunUntilDone = require 'WFRxRunUntilDone'

local LrmTHLibraryLoaded, _ = pcall( require, 'LrmTHLibrary' )

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

local LrmTestAppMessageProcessor = {}

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

local WFRxTestCaseRunner = {

	_testName = false,
	
	_ffns = false,
	WFCloseSupport.addCloseSupportMethods,
}

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

function WFRxTestCaseRunner:__init( testName )

	WFArguments.check( 'WFRxTestCaseRunner', 'string' )
	
	self._testName = testName
	self._ffns = {}
	
end

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

function WFRxTestCaseRunner:testName()

	return self._testName
	
end

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

function WFRxTestCaseRunner:finally( fn )

	table.insert( self._ffns, fn )
	
end

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

function WFRxTestCaseRunner:close()

	for i, fn in pairs( self._ffns ) do
	
		fn()
		
	end
	
end

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


WFRxTestCaseRunner = Rx.Class( 'WFRxTestCaseRunner', WFRxTestCaseRunner )

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

local HelperModels = {}

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

function LrmTestAppMessageProcessor.makeLibraryModel()

	local catalogService, wfCatalog, catalogId = LrmCatalogTestHelper.makeCatalogService()

	local documentObserver

	if LrmTHLibraryLoaded then

		documentObserver = wfCatalog:docStore()
			:scannedFilteredMappedChangesFeed( 'LrmTHLibrary', 'scanFilterMap', 'THLibrary-scanToken' )
			:subscribe()

	end

	local purgeAgent = LrmOzPurgeAgent( catalogService )
	local syncManager = LrmSyncManager {
		catalog = catalogService,
		catalogId = catalogId,
		isWiFiOnlySync = Rx.BehaviorSubject( false ),
		isReachable = Rx.BehaviorSubject( 'wifi' ),
		forceUpgrade = Rx.BehaviorSubject( false ),
		isAuthenticatedUser = Rx.BehaviorSubject( true ),
		entitlement = Rx.BehaviorSubject( { status = 'subscription' } ),
		syncEnabled = Rx.BehaviorSubject( false ),
		isAppInBackground = Rx.BehaviorSubject( false ),
	}

	return {
		
		_wfCatalogStream = catalogService:getWfCatalog(),
		_syncManager = syncManager,
		_wfCatalog = wfCatalog,
		catalog = catalogService,
		documentObserver = documentObserver,
		purgeAgent = purgeAgent,

		valueB = KSReactive.variableB( WFUnknown.value() ),

		models = WFModelsUtils.aggregateModels( LrmLibraryModelFactory.makeLibrarySubModels(), HelperModels ),

		events = {

			applyOverlayToDocument = function( parent, docType, docId, overlay )

				parent.catalog:docStore():applyOverlayToDocumentP {
					docType = docType,
					docId = docId,
					overlay = overlay,
				}
				:runUntilDone()

			end,

			applyOverlay = function( parent, overlay )

				parent.catalog:docStore():applyOverlay( overlay )
					:call( WFRxRunUntilDone )

			end,

			bulkApplyOverlay = function( parent, overlay )

				parent.catalog:docStore():bulkApplyOverlay( overlay )
					:call( WFRxRunUntilDone )

			end,

			deleteDoc = function( parent, docId, revId )

				parent.catalog:docStore():deleteDoc( docId, revId )
					:call( WFRxRunUntilDone )

			end,
		}
	}

end

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

function LrmTestAppMessageProcessor.makeOzUserTestSessionModel( testName )

	local rxTestMock = WFRxTestCaseRunner( testName )
	
	local catalogTestSession = WFCatTestSession( rxTestMock )
	
	local catalog = catalogTestSession:catalog():shareReplay( 1 )
	
	local tokens = catalog:flatMapLatest( function( wfCatalog )
		
		return wfCatalog:ozUser():fetchTokens()
		
	end )
	:map( function( accessToken, refreshToken, deviceToken )
	
		return {
			accessToken = accessToken,
		}
		
	end )
	
	local modelResult = Rx.Observable.combineLatest( function( wfCatalog, tokens )
	
		WFTableMerge.applyOverlay( tokens, {
			ozUserId = wfCatalog:ozUserId(),
			ozCatalogId = wfCatalog:ozCatalogId(),
		} )
		
		return tokens
		
	end, catalog, tokens )
	
	return {
		
		_catalogTestSession = catalogTestSession,
		
		value = modelResult,
		
		close = function( self )
		
			self._catalogTestSession:close()
			rxTestMock:close()
			
		end
	}
	
end

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

return LrmTestAppMessageProcessor
