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

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.

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

local Rx = require 'Rx'
local Observable = Rx.Observable

	-- WF.core.reactive
local KSReactive = require 'KSReactive'
local KSPromises = require 'KSPromises'

	-- WF.core.utils
local WFUnknown = require 'WFUnknown'
local WFCatUtils = require 'WFCatUtils'
local WFTableMerge = require 'WFTableMerge'

	-- WF.core.os
local KSDate = require 'KSDate'
local WFRxThrottledBatchedApplyOverlayToIds = require "WFRxThrottledBatchedApplyOverlayToIds"

local logger = require 'WFLogger' ( 'LrmLibraryReviewModelImp' )

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

local LrmLibraryReviewModelImp = {}

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

function LrmLibraryReviewModelImp:setAssetFlagStatus( flagStatus, assetIds )

	local resultB = KSReactive.variableB( WFUnknown.value() )
	
	local catalog = self.catalog
	
	local function setFlagStatusP( assetId, userId )
	
		local baseDocValue = WFCatUtils.createBaseOverlayWithUserUpdatedField( assetId )
	
		local flagOverlay = {
			type = 'asset',
			reviews = {
				[ userId ] = {
					flag = flagStatus,
					date = KSDate.timeInIso8601FormatNearestSecond(),
				},
			},
		}
		
		WFTableMerge.applyOverlay( flagOverlay, baseDocValue )
		
		return catalog:docStore():applyOverlayP( flagOverlay )
			
	end
	
	catalog:ozUserIdP()
		:mapDataP_new( function( userId )
		
			return KSPromises.allP( function( assetId )
			
				return setFlagStatusP( assetId, userId )
				
			end, assetIds )
			
		end )
	
		:whenResolvedDo( function( status, data )
		
			if status == 'data' then
			
				resultB:set( { state = true } )
				
			else
			
				resultB:set( { state = false, error = data } )
				
			end
			
		end )
		:runUntilDone()
		
	return {
		valueB = resultB,
	}
	
end

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

function LrmLibraryReviewModelImp:setAssetRating( rating, assetIds )

	local resultB = KSReactive.variableB( WFUnknown.value() )
	
	local catalog = self.catalog
	
	local function setRatingP( assetId, userId )
	
		local baseDocValue = WFCatUtils.createBaseOverlayWithUserUpdatedField( assetId )
		
		local ratingOverlay = {
			type = 'asset',
			ratings = {
				[ userId ] = {
					rating = rating,
					date = KSDate.timeInIso8601FormatNearestSecond(),
				},
			},
		}
		
		WFTableMerge.applyOverlay( ratingOverlay, baseDocValue )
		
		return catalog:docStore():applyOverlayP( ratingOverlay )
		
	end
	
	catalog:ozUserIdP()
		:mapDataP_new( function( userId )
	
			return KSPromises.allP( function( assetId )
			
				return setRatingP( assetId, userId )
				
			end, assetIds )
			
		end )
		:whenResolvedDo( function( status, data )
		
			if status == 'data' then
			
				resultB:set( { state = true } )
				
			else
			
				resultB:set( { state = false, error = data } )
				
			end
			
		end )
		:runUntilDone()
	
	return {
		valueB = resultB,
	}
	
end

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

function LrmLibraryReviewModelImp:setAssetMetadata( assetIds, title, caption, copyright, rating, flagStatus)

	local function updateInfo(wfCatalog, docIds, title, caption, copyright, rating, flagStatus)

		local userId = wfCatalog:ozUserId()
		local timestamp = KSDate.timeInIso8601FormatNearestSecond()
		local userUpdated = KSDate.timeInIso8601Format()

		local overlay = {
			userUpdated = userUpdated
		}

		if title or caption or copyright then
			local dc = {}
			if copyright then
				dc.rights = copyright
			end
			if title then
				dc.title = title
			end
			if caption then
				dc.description = caption
			end
			overlay.xmp = {
				dc = dc
			}
		end

		if rating then
			overlay.ratings = {
				[userId] = {
					rating = rating,
					date = timestamp,
				},
			}
		end

		if flagStatus then
			overlay.reviews = {
				[userId] = {
					flag = flagStatus,
					date = timestamp,
				},
			}
		end

		return WFRxThrottledBatchedApplyOverlayToIds( "LrmLibraryReviewModelImp_setAssetMetadata", wfCatalog:docStore(), overlay, docIds, 100, 10 )

	end

	local catalog = self.catalog
	local result = catalog:getWfCatalog()
		:flatMap( function( wfCatalog )
			return updateInfo(wfCatalog, assetIds, title, caption, copyright, rating, flagStatus)
		end)
		:map( function()

			return { state = true }

		end)
		:catch( function( maybeErrorMessage )

			if maybeErrorMessage then
				logger:errorf( "setAssetMetadata Failed: %s", maybeErrorMessage )
			end

			return Observable.just( { state = false } )

		end )


	return {
		value = result
	}
end

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

return LrmLibraryReviewModelImp
