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

NmbPurgeControl.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2018 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 WFFunctionUtils = require "WFFunctionUtils"

local Rx = require "Rx"

local logger = require "WFLogger"( "NmbPurgeControl" )

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

local function applyProtectOrReleaseToVolumeAgent( 
				volumeAgent, volumeAgentAPI, assetIds )

	local f = volumeAgent[ volumeAgentAPI ]

	if type( f ) ~= "function" then

		logger:warnf( "volumeAgent %s doesn't support API: %s",
						volumeAgent, volumeAgentAPI )

		return

	end

	f( volumeAgent, assetIds )

end

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

local function applyProtectOrReleaseToVolumeAgents( 
					wfCatalog, volumeAgentAPI, assetIds )

	WFFunctionUtils.map( 
		applyProtectOrReleaseToVolumeAgent,
			wfCatalog:getAllVolumeAgentsAsArray(), volumeAgentAPI, assetIds )

	return string.format( "%s( %s assets )", volumeAgentAPI, #assetIds )

end 

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

local function makeModel( wfCatalogStream )

	local protectOrReleaseCommandStream = Rx.Subject()

	return  {

		value = wfCatalogStream
					:flatMap(
						function( wfCatalog )

							return protectOrReleaseCommandStream 
									:map(
										function( volumeAgentAPI, assetIds )

											return applyProtectOrReleaseToVolumeAgents(
													wfCatalog, volumeAgentAPI,
													assetIds )

										end )

						end ),

		events = {

			protectFromPurge = 
				function( _, assetIds )

					protectOrReleaseCommandStream
						:onNext( "protectFromPurge", assetIds )

				end,

			releaseProtectionFromPurge = 
				function( _, assetIds )

					protectOrReleaseCommandStream
						:onNext( "releaseProtectionFromPurge", assetIds )

				end,

		}
	}

end

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

return {

	makeModel = makeModel,

}
