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

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.utils
local KSTableUtils = require 'KSTableUtils'
local WFOzSyncConstants = require 'WFOzSyncConstants'

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

local derefOpt = KSTableUtils.derefOpt

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

local OzSyncMetadataMapper = {}

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

local kFieldsToMap = { 'ratings', 'reviews' }

local kGenericId = WFOzSyncConstants.kGlobalDocumentId

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

function OzSyncMetadataMapper.remapGlobalDocumentId( userId, payload  )

	for _, k in ipairs( kFieldsToMap ) do
		
		local section = derefOpt( payload, k , kGenericId )
		
		if section then
		
			if not payload[ k ][ userId ] then
				payload[ k ][ userId ] = section
			end
			
			payload[ k ][ kGenericId ] = nil
			
		end
			
	end
	
	local importedBy = derefOpt( payload, 'importSource', 'importedBy' )
	
	if importedBy == kGenericId then
	
		payload.importSource.importedBy = userId
		
	end
	
end

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

function OzSyncMetadataMapper.removeEmptyTables( payload )

	local reviews = derefOpt( payload, 'reviews' )
	local ratings = derefOpt( payload, 'ratings' )
	
	if type( reviews ) == 'table' and not next( reviews ) then
		payload['reviews'] = nil
	end
	
	if type( ratings ) == 'table' and not next( ratings ) then
		payload['ratings'] = nil
	end
	
	return payload
	
end

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

return OzSyncMetadataMapper
