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

NmbSmartAlbums.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2024 Adobe
All Rights Reserved.

NOTICE: All information contained herein is, and remains
the property of Adobe and its suppliers, if any. The intellectual
and technical concepts contained herein are proprietary to Adobe
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.
------------------------------------------------------------------------------]]

local KSTableUtils = require 'KSTableUtils'
local WFArguments = require 'WFArguments'
local WFCatIndexUtils = require 'WFCatIndexUtils'
local WFMsgPack = require 'WFMsgPack'

local check = WFArguments.check
local derefOpt = KSTableUtils.derefOpt

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

local NmbSmartAlbums = {}

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

function NmbSmartAlbums.generateIndexSchema( indexStoreSchema )
	
	check( 'WFRxIndexStoreSchema' )
	
	indexStoreSchema:addTable {
		
		sql = [[CREATE TABLE smart_albums( 
					smart_albumId,
					name, 
					parentId,
					updateTimestamp, 
					createdTimestamp,
					predicates)]],
		
		useLocalId = true,
		
		hasOneRowPerDocument = true,
		
		relevantTypeSubtypeTuples = {
			{ 'album', 'smart' },
		},
		
		map = function( docValue, emit )
			
			if WFCatIndexUtils.isValidSmartAlbumDocument( docValue ) then
				
				local ozCreated = derefOpt( docValue, '_serverProvidedMetadata', 'created' )
				local ozUpdated = derefOpt( docValue, '_serverProvidedMetadata', 'updated' )
				
				local smart_albumId = docValue._id
				
				local created = docValue.userCreated or ozCreated 
				local updated = docValue.userUpdated or ozUpdated
				
				local name = docValue.name
				
				local parentId = derefOpt( docValue, 'parent', 'id' )
				
				local predicates = derefOpt( docValue, 'predicates' )
				
				local predicatesStr = next( predicates ) and WFMsgPack.pack( predicates ) or nil
				
				if created and name and updated then
					emit( smart_albumId, name, parentId, updated, created, predicatesStr )
				end
			end
			
		end,
		
	}
	
	indexStoreSchema:addIndex [[CREATE INDEX smart_album_id ON smart_albums( smart_albumId )]]

end

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

return NmbSmartAlbums
