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

LrmMigrateCacheIndexdefinitions.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 WFArguments = require 'WFArguments'
local WFRxIndexStoreSchema = require "WFRxIndexStoreSchema"

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


local OzCatalogUploadStatus = require "OzCatalogUploadStatus"

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

local derefOpt = assert( KSTableUtils.derefOpt )

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

local check = assert( WFArguments.check )

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

-- @mark LrmCacheIndexdefinitions namespace

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

local LrmCacheIndexdefinitions = {}

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

--[[
	These constants are only used when existing photos (imported on 2011-08-12
	and before are in the system and we didn't capture the rendition size.
]]--

local defaultSizeForRendition = {
	original = 20000000,
	proxy = 943718,
	preview = 150000,
	thumbnail = 12000,
	thumbnail2x = 48000,
}

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

function LrmCacheIndexdefinitions.coreMD5FromDocValue( docValue )
	
	local renditions = { 'thumbnail', 'thumbnail2x', 'preview', 'master' }
	local results = {}
	local localOnly = docValue._localOnly
	
	for index, rendition in ipairs( renditions ) do
		local md5 = derefOpt( localOnly, rendition, 'md5' )
		results[ index ] = md5
	end
	
	return unpack ( results, 1, 4 )

end

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

function LrmCacheIndexdefinitions.generateIndexSchema( indexStoreSchema )

	check( 'WFRxIndexStoreSchema' )

	-- table cacheReferences

	indexStoreSchema:addTable {

		sql = [[CREATE TABLE cacheReferences( md5, renditionName, size, epoch, hasUploaded )]],

		relevantTypeSubtypeTuples = {
			{ 'asset', '*' }
		},

		map = function( docValue, emit )

			if docValue.type ~= 'asset' then
				return
			end
			
			local localOnly = docValue._localOnly
			
			local serverLinks =
				  ( docValue._serverProvidedMetadata
				and docValue._serverProvidedMetadata.links ) or {}

			local function emitForRenditionName( renditionName, ozNameForRendition )
			
				local renditionInfo = derefOpt( docValue, '_localOnly', renditionName )
				
				if not renditionInfo then
					return
				end
				
				-- we aren't making destructive edits to originals yet, so we do not upload
				-- originals other than the base original
				
				local renditionKey
				
				if renditionName == 'latestOriginal' then
					renditionKey = OzCatalogUploadStatus.checkAndCorrectLocalPath(
									localOnly.latestOriginal
										and localOnly.latestOriginal.filePath )
				elseif renditionName == 'original' then
					-- Temporary check to correct the local file path and replace
					-- 'Adobe Carousel Library.cr' with 'Adobe Revel Library.cr'
			
					-- FIXME [ngautam 2011-11-15] This should really be done via an upgrade process
					-- that updates the database with the correct file paths but this is not
					-- feasible in the current time frame.
					renditionKey = OzCatalogUploadStatus.checkAndCorrectLocalPath( localOnly.originalFilePath )
				elseif renditionName == 'proxy' then
					local filePath = derefOpt( docValue, '_localOnly', renditionName )
					filePath = derefOpt( filePath, 'filePath' )
					renditionKey = OzCatalogUploadStatus.checkAndCorrectLocalPath( filePath )
				else
					renditionKey = renditionInfo.md5
				end

				if renditionInfo and renditionKey then
				
					local serverLinksForRendition = serverLinks[ ozNameForRendition ]
					local shouldUpload
					
					if ( renditionName ~= 'latestOriginal' and renditionName ~= 'proxy' ) then
						shouldUpload = ( not serverLinksForRendition )
							or serverLinksForRendition.invalid
							or renditionInfo.revId == 'pending'
					else
						-- We don't upload the latest original
						shouldUpload = false
					end
						
				
					emit( renditionKey,
						  renditionName,
						  renditionInfo.size or defaultSizeForRendition[ renditionName ] or 1000000,
						  renditionInfo.epoch or 1,
						  shouldUpload and 0 or 1 )
				
--					cacheReferencesLog:debug( "photoId = %s | renditionName = %s | size = %s | epoch  %s | hasUploaded = %s",
--						docValue._docId, renditionName, renditionInfo.size, renditionInfo.epoch or 1,
--						not shouldUpload )
				
				end
			
			end

			emitForRenditionName( 'thumbnail', '/rels/rendition_type/144h' )
			emitForRenditionName( 'thumbnail2x', '/rels/rendition_type/thumbnail2x' )
			emitForRenditionName( 'preview', '/rels/rendition_type/2048' )
			emitForRenditionName( 'proxy', '/rels/proxy_type/2560' )
			emitForRenditionName( 'original', '/rels/master' )
			emitForRenditionName( 'latestOriginal', '' )

		end,

	}

	indexStoreSchema:addIndex [[CREATE INDEX cacheReferences_epoch ON cacheReferences( epoch DESC, size )]]
	indexStoreSchema:addIndex [[CREATE INDEX cacheReferences_md5 ON cacheReferences( md5 ASC, docId )]]
	indexStoreSchema:addIndex [[CREATE INDEX cacheReferences_potentialVictims
		ON cacheReferences( epoch ASC, size DESC, docId )]]
	indexStoreSchema:addIndex [[CREATE INDEX cacheReferences_hasUploaded ON cacheReferences( hasUploaded )]]
	indexStoreSchema:addIndex [[CREATE INDEX cacheReferences_renditionName ON cacheReferences( renditionName )]]

end

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

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


local indexStoreSchema = WFRxIndexStoreSchema( )

indexStoreSchema:addDatabaseInitRoutine( require 'WFSQLiteSetLogicImp'.registerSetModule )

LrmCacheIndexdefinitions.generateIndexSchema( indexStoreSchema )

LrmCacheIndexdefinitions.indexStoreSchema = indexStoreSchema

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

return LrmCacheIndexdefinitions
