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

WFCatImportManifestRootAlbumProcessor.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2017 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.

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

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

	-- WF.core.utils
local KSIdGenerator = require 'KSIdGenerator'

	-- WF.oz_client.managed_catalog
local WFCatAlbums = require 'WFCatAlbums'

	-- WF.oz_client.managed_catalog.import
local WFCatImportManifestConstants = require 'WFCatImportManifestConstants'
local WFCatImportManifestProcessorBase = require 'WFCatImportManifestProcessorBase'
local WFCatImportManifestProcessorUtils = require 'WFCatImportManifestProcessorUtils'

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

local function addAlbumStatus( manifestStatusDatabase, local_id, oz_id, oz_name, status )
	
	local statusData = { {
		local_id = local_id,
		oz_id = oz_id,
		oz_name = oz_name,
		status = status,
	} }
	
	return manifestStatusDatabase:writeData( 'addOrReplaceAlbumStatus', statusData )
		:ignoreElements()
	
end

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

local function updateAlbumStatus( manifestStatusDatabase, albums, status )
	
	local statuses = {}
	for i, album in ipairs( albums ) do
		statuses[ #statuses + 1 ] = {
			local_id = album.local_id,
			status = status,
		}
	end
	
	return manifestStatusDatabase:writeData( 'updateAlbumStatus', statuses )
		:ignoreElements()
	
end

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

local function getDocstoreLocalIdForOzId( catalog, ozId )
	
	if not ozId then
		return Observable.just()
	end
	
	return catalog:docStore():docValue( ozId )
	
end

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

local function getAlbumNamesObservable( catalog, idCache, parentOzId )
	
	return Observable.zip(
		WFCatAlbums.getAlbumsList( catalog ):take( 1 ),
		getDocstoreLocalIdForOzId( catalog, parentOzId )
	)
		:map( function( albumList, parentDocValue  )
		
			local parentLocalId = parentDocValue and parentDocValue._localId
			local takenAlbumNames = {}
			
			for _, albumInfo in ipairs( albumList ) do
				
				if albumInfo.parentId == parentLocalId then
					takenAlbumNames[ albumInfo.name ] = true
				
				end
			end
			
			return takenAlbumNames

		end )
		
end

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

local function createOrFetchAlbumImp( self, catalog, idCache, manifestStatusDatabase, 
	messageHandler, localId, name, parentOzId, importSource, manifestSourceId )

	if self:_isAlreadyProcessed( localId ) then
		
		local ozId = idCache:getOzIdForLocalId( WFCatImportManifestConstants.idCacheSets.albums, localId )
		return Observable.just( ozId )
	end
	
	local pendingUUID = self._processedRows[ localId ] and self._processedRows[ localId ].oz_id
	local uuid = pendingUUID or KSIdGenerator.uuidInLowercaseHex( )

	return addAlbumStatus( manifestStatusDatabase, localId, uuid, name, WFCatImportManifestConstants.status.pending )
		:defaultIfEmpty()
		:flatMap( function()
			
			local createAlbumOrFolderObs
			if parentOzId then
				createAlbumOrFolderObs = WFCatAlbums.createAlbum( catalog, name, parentOzId, false, importSource, uuid, manifestSourceId )
			else
				createAlbumOrFolderObs = WFCatAlbums.createFolder( catalog, name, parentOzId, importSource, uuid, manifestSourceId )
			end
			
			return createAlbumOrFolderObs
				:flatMap( function( _, ozId )
				
					local updateStatusObservable
					if not ozId then
						self:_sendMessage( messageHandler, WFCatImportManifestConstants.messages.rootAlbumCreateError.code, { { name, localId } } )
						updateStatusObservable = updateAlbumStatus( manifestStatusDatabase, { { local_id = localId } }, WFCatImportManifestConstants.status.failure )
						self:_updateError( messageHandler, 1 )
					else
						-- Save the new doc id
						idCache:setOzIdForLocalId( WFCatImportManifestConstants.idCacheSets.albums, localId, ozId )
						updateStatusObservable = updateAlbumStatus( manifestStatusDatabase, { { local_id = localId } }, WFCatImportManifestConstants.status.success )
						self:_updateSuccess( messageHandler, 1 )
					end
					
					return updateStatusObservable
						:defaultIfEmpty()
						:map( function()
							
							if ozId then
								return ozId
							end 
							
							error( "Root album creation failed: Name:"..tostring( name ) )
						end )
				end )
		end )

end
--------------------------------------------------------------------------------

local function createOrFetchRootAlbum( self, catalog, idCache, manifestStatusDatabase, messageHandler, contextInfo, lrcatStoreProviderId, manifestSourceId )

	local importSource = lrcatStoreProviderId and {
		lrcatStoreProviderId = lrcatStoreProviderId,
	}
	
	local parentOzId = self._params.parentLocalId 
			and idCache:getOzIdForLocalId( WFCatImportManifestConstants.idCacheSets.albums, self._params.parentLocalId )
	
	return getAlbumNamesObservable( catalog, idCache, parentOzId )
	
		:map( function( takenAlbumNames )
			
			local albumName = contextInfo[ self._params.albumNameKey ]
			return WFCatImportManifestProcessorUtils.findUniqueName( albumName, takenAlbumNames )
		end )
		
		:flatMap( function( albumName )
			
			local localId = self._params.localId
			return createOrFetchAlbumImp( self, catalog, idCache, manifestStatusDatabase, messageHandler, localId, albumName, parentOzId, importSource, manifestSourceId )
		end )
		
end

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

local WFCatImportManifestRootAlbumProcessor = {
	
	WFCatImportManifestProcessorBase,
	
	_params = false,
}

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

function WFCatImportManifestRootAlbumProcessor:__init( params )

	self._stageName = params.stageName
	self._params = params
	
	self._messageCodeCompleted = WFCatImportManifestConstants.messages.rootAlbumProcessingComplete.code
	self._messageCodeErrorCount = WFCatImportManifestConstants.messages.rootAlbumProcessingErrorCount.code
	self._messageCodeGenericError = WFCatImportManifestConstants.messages.rootAlbumProcessingError.code
end

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

function WFCatImportManifestRootAlbumProcessor:setup( catalog, manifestDatabase, manifestStatusDatabase, idCache, messageHandler )

	return self:WFCatImportManifestProcessorBase_setup( catalog, 
		manifestStatusDatabase, idCache, messageHandler, 'selectRootAlbumsStatus',
		WFCatImportManifestConstants.idCacheSets.albums )

end

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

function WFCatImportManifestRootAlbumProcessor:processImpObservable( catalog, profileCatalog, wfCatSynchronizer, 
			manifestDatabase, manifestStatusDatabase, idCache, messageHandler, contextInfo )
	
	self._totalCount = 1
	
	return Observable.zip(
			WFCatImportManifestProcessorUtils.maybeReadLrCatStoreProviderId( manifestDatabase ),
			WFCatImportManifestProcessorUtils.maybeReadManifestSourceId( manifestDatabase )
		)
	
		:flatMap( function( lrcatStoreProviderId, manifestSourceId )
			
			-- Create both the root album-set and all-photos album
			return createOrFetchRootAlbum( self, catalog, idCache, manifestStatusDatabase, messageHandler, contextInfo, lrcatStoreProviderId, manifestSourceId )
		end )
		
		:ignoreElements()
		
end

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

local WFCatImportManifestRootAlbumProcessorClass = Rx.Class 'WFCatImportManifestRootAlbumProcessor'( WFCatImportManifestRootAlbumProcessor )

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

local kRootAlbumLocalId = WFCatImportManifestConstants.kRootAlbumLocalId

local kParamsForAlbum = {
	
	rootAlbumSet = {
		stageName = WFCatImportManifestConstants.stageNames.rootAlbumSet,
		localId = kRootAlbumLocalId,
		parentLocalId = nil,
		albumNameKey = "rootAlbumName",
	},
	
	allPhotosAlbum = {
		stageName = WFCatImportManifestConstants.stageNames.rootAlbumAllPhotos,
		localId = WFCatImportManifestConstants.kManifestAllPhotoAlbumLocalId,
		parentLocalId = kRootAlbumLocalId,
		albumNameKey = "allPhotosAlbumName",
	},
}
--------------------------------------------------------------------------------

local function getRootAlbumSetProcessor()
	
	return WFCatImportManifestRootAlbumProcessorClass( 
		kParamsForAlbum.rootAlbumSet )
end

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

local function getAllPhotosAlbumProcessor()
	
	return WFCatImportManifestRootAlbumProcessorClass( 
		kParamsForAlbum.allPhotosAlbum )
end

--------------------------------------------------------------------------------
return {
	getRootAlbumSetProcessor = getRootAlbumSetProcessor,
	getAllPhotosAlbumProcessor = getAllPhotosAlbumProcessor,
}
