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

LrmAlbumsIndexDefinitions.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2016 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 KSStringUtils = require "KSStringUtils"
local WFArguments = require 'WFArguments'
local WFPlatformInfo = { isAndroid = function() return true end } -- TODO [immisch 2020-06-18] remove ASAP, but avoid a reindex at all costs for now

local LrmCatSyncStatus = require 'LrmCatSyncStatus'
--------------------------------------------------------------------------------

local check = assert( WFArguments.check )

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

-- @mark LrmCatAlbum namespace

local LrmAlbumsIndexDefinitions = {}

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

function LrmAlbumsIndexDefinitions.generateIndexSchema( indexStoreSchema )

	check( 'WFRxIndexStoreSchema' )

	-- table albums

	indexStoreSchema:addTable  {

		sql = [[CREATE TABLE albums( 
				name, 
				nameLC, 
				updateTimeStamp, 
				localTimeStamp, 
				useOffline, 
				coverId, 
				parentId, 
				subtype, 
				hideInOrganize,
				syncStatus,
				spaceId,
				hasDisplayFilters,
				title )]],
		
		updateLazily = false,
		
		relevantTypeSubtypeTuples = {
			{ 'album', 'collection' },
			{ 'album', 'collection_set' },
			{ 'album', 'topic' },
			{ 'album', 'cluster' }
		},
		
		hasOneRowPerDocument = true,
		
		map = function( docValue, emit )

			if docValue and docValue.type == 'album'
					and ( docValue.subtype == 'collection' or docValue.subtype == 'collection_set'
							-- Clusters and topics are needed for the supporting the best photos feature in Android.
							or ( WFPlatformInfo.isAndroid and (docValue.subtype == 'topic' or docValue.subtype == 'cluster'))
						)
					and not docValue._deleted then
			
				local name = docValue.name or ""
				local nameFormatted =  KSStringUtils.lower( name )
				nameFormatted = KSStringUtils.trim( nameFormatted )
				local id = docValue._id or docValue._docId
				local updateTimeStamp = docValue.userUpdated or docValue.updated
				local localTimeStamp = docValue._localOnly and docValue._localOnly.updateTimeStamp
				
				-- INFO [pkamin 2018-04-23]: https://wiki.corp.adobe.com/display/photo/Adhoc+Album+Reconciliation+Rollout
				-- Temporary change for the June 2018 release
				
				local hideInOrganize = KSTableUtils.derefOpt( docValue, 'hideInOrganize' )
				if hideInOrganize then
					hideInOrganize = hideInOrganize == true
				else
					hideInOrganize = false
				end
				
				local serverUpdatedTime = KSTableUtils.derefOpt( docValue, '_serverProvidedMetadata', 'updated' )
				
				if not updateTimeStamp then
					updateTimeStamp = localTimeStamp
				end
				
				if not updateTimeStamp then
					updateTimeStamp = serverUpdatedTime
				end
				
				local useOffline = 0
				if docValue._localOnly and docValue._localOnly.useOffline then
					useOffline = 1
				end
				
				local coverAssetId = docValue.cover and docValue.cover.id
				
				local parentId = docValue.parent and docValue.parent.id or 'root'

				local subtype = docValue.subtype
				
				local spaceId = docValue._spaceId

				local syncStatus = LrmCatSyncStatus.getAlbumSyncStatus( docValue )

				local ratingAtLeast = KSTableUtils.derefOpt( docValue, 'presentation', 'filters', 'ratingAtLeast' )
				ratingAtLeast = tonumber( ratingAtLeast ) or 0
				
				local pickedOnly = KSTableUtils.derefOpt( docValue, 'presentation', 'filters', 'pickedOnly' ) or false
				
				local hasDisplayFilters = ratingAtLeast > 0 or pickedOnly
				hasDisplayFilters = hasDisplayFilters and 1 or 0

				local title = KSTableUtils.derefOpt( docValue, 'story', 'title' )

				if id and name then
				
					emit( name, nameFormatted, updateTimeStamp, localTimeStamp, useOffline, 
							coverAssetId, parentId, subtype, hideInOrganize, syncStatus, spaceId,
							hasDisplayFilters, title )
							
				end
			
			end

		end,

	}

	indexStoreSchema:addIndex [[CREATE INDEX albums_useOffline ON albums( useOffline )]]

	-- table album_assets
	
	indexStoreSchema:addTable {

		sql = [[CREATE TABLE album_asset( assetId, userId, albumId, updateTimeStamp, sortOrder, isCover )]],
		
		updateLazily = false,
		
		relevantTypeSubtypeTuples = {
			{ 'album_asset', 'NULL' }
		},
		
		hasOneRowPerDocument = true,
		
		map = function( docValue, emit )
	
			if docValue and not docValue._deleted then
			
				if docValue.type == 'album_asset' then

					local albumId = docValue.album and docValue.album.id
					local assetId = docValue.asset and docValue.asset.id
					local updateTimeStamp = docValue.userUpdated or docValue.updated
					local sortOrder = docValue.order
					
					if not updateTimeStamp then
						updateTimeStamp = KSTableUtils.derefOpt( docValue, '_serverProvidedMetadata',
																	'updated' )
					end
						
					local isCover = docValue.cover or false

					local userId = docValue.added_by
					if userId and string.len( userId ) > 32 then
						userId = userId:sub( -32 )
					end

					if albumId and assetId then
						emit( assetId, userId, albumId, updateTimeStamp, sortOrder, isCover )
					end
					
				end
				
			end

		end,
	}

	indexStoreSchema:addIndex [[CREATE INDEX album_asset_index ON album_asset( albumId, assetId )]]

	indexStoreSchema:addIndex [[CREATE INDEX album_asset_activity_date_userId ON album_asset( updateTimeStamp DESC, userId )]]

end

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

return LrmAlbumsIndexDefinitions
