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

LrmPresetsProfilesIndexDefinitions.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2018 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 WFPlatformInfo = require 'WFPlatformInfo'

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

local check = assert( WFArguments.check )

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

-- @mark LrmKeywordsIndexDefinitions namespace

local LrmPresetsProfilesIndexDefinitions = {}

--------------------------------------------------------------------------------
local logger = require 'WFLogger' '_preset_profile_dcp'
 :setLevel 'debug'

function LrmPresetsProfilesIndexDefinitions.generateIndexSchema( indexStoreSchema )

	check( 'WFRxIndexStoreSchema' )

	-- table presetsProfiles
	if WFPlatformInfo.isAndroid then

		local KSStringUtils = require 'KSStringUtils'

		indexStoreSchema:addTable  {

			sql = [[CREATE TABLE presetsProfiles( type, sha256, needsSave )]],

			relevantTypeSubtypeTuples = {
				{ 'asset', 'preset' },
				{ 'asset', 'profile' }
			},

			hasOneRowPerDocument = true,

			map = function( docValue, emit )

				if docValue and docValue.type == 'asset'
						and ( docValue.subtype == 'preset' or docValue.subtype == 'profile')
						and not docValue._deleted then

					if not ( docValue._id or docValue._docId ) then
						return
					end

					local localOnlyPath = KSTableUtils.derefOpt( docValue, "_localOnly", "files", "presetProfile", "path" )
					local relsMaster = KSTableUtils.derefOpt( docValue, "_serverProvidedMetadata", "links", "/rels/master", "href" )
					local isInvalid = KSTableUtils.derefOpt( docValue, "_serverProvidedMetadata", "links", "/rels/master", "invalid" )

					if not localOnlyPath and not relsMaster then
						-- document originated from remote but binary is not yet available
						return
					end

					if isInvalid then
						-- Doc has been updated by remote but new binary has not been uploaded yet.
						-- Ignore for now.
						return
					end

					local subtype = docValue.subtype

					local incomingSha256 = KSTableUtils.derefOpt( docValue, "importSource", "sha256" )

					local localOnlySha256 = KSTableUtils.derefOpt( docValue, "_localOnly", "files", "presetProfile", "sha256" )

					local needsSave = incomingSha256 ~= localOnlySha256 -- will catch renames as well

					if needsSave then
						emit( subtype, incomingSha256, 1 )
					else
						emit( subtype, incomingSha256, 0 )
					end

				end

			end,

		}

		indexStoreSchema:addTable  {

			sql = [[CREATE TABLE CustomCameraProfiles( modelName, type, sha256, digest, url, filename, needsSave )]],

			updateLazily = false, -- don't wait for the table to be used. Do indexing ASAP

			relevantTypeSubtypeTuples = {
				{ 'asset', 'camera_profile' },
			},

			hasOneRwoPerDocument = true,

			map = function( docValue, emit )

				if docValue and docValue.type == 'asset'
						and ( docValue.subtype == 'camera_profile' )
						and not docValue._deleted then

					local subtype = docValue.subtype
					local incomingSha256 = KSTableUtils.derefOpt( docValue, "importSource", "sha256" )
					local localOnlySha256 = KSTableUtils.derefOpt( docValue, "_localOnly", "files", "dcpProfile", "sha256" )

					local needsSave = incomingSha256 ~= localOnlySha256 -- will catch renames as well
					local modelName = KSTableUtils.derefOpt( docValue, 'model' )
					local url = KSTableUtils.derefOpt( docValue, '_serverProvidedMetadata', 'links', '/rels/master', 'href')
					local digest = KSTableUtils.derefOpt( docValue, 'cameraProfileDigest')
					local filename = docValue.fileName

					modelName = modelName and KSStringUtils.upper( modelName ) or modelName
					digest = digest and KSStringUtils.upper( digest ) or digest

					logger:debugf('cameraModel:%s, needsSave:%s, digest:%s', modelName, needsSave, digest)

					if needsSave then
						emit( modelName, subtype, incomingSha256, digest, url, filename, 1 )
					else
						emit( modelName, subtype, incomingSha256, digest, url, filename, 0 )
					end

				end

			end,

		}

		indexStoreSchema:addIndex [[CREATE INDEX CustomCameraProfiles_modelname ON CustomCameraProfiles( needsSave, modelName )]]
		indexStoreSchema:addIndex [[CREATE INDEX CustomCameraProfiles_modelname_digest ON CustomCameraProfiles ( digest, modelName )]]

	else

		indexStoreSchema:addTable  {

			sql = [[CREATE TABLE presetsProfiles( cameraModel, sha256, needsSave )]],

			updateLazily = false,

			relevantTypeSubtypeTuples = {
				{ 'asset', 'preset' },
				{ 'asset', 'profile' },
				{ 'asset', 'camera_profile' },
			},

			hasOneRowPerDocument = true,

			map = function( docValue, emit )

				if docValue and docValue.type == 'asset'
						and ( docValue.subtype == 'preset' or docValue.subtype == 'profile' or docValue.subtype == "camera_profile")
						and not docValue._deleted then

					local id = docValue._id or docValue._docId
					if not id then
						return
					end

					local localOnlyPath = KSTableUtils.derefOpt( docValue, "_localOnly", "files", "presetProfile", "path" )
					local relsMaster = KSTableUtils.derefOpt( docValue, "_serverProvidedMetadata", "links", "/rels/master", "href" )
					local isInvalid = KSTableUtils.derefOpt( docValue, "_serverProvidedMetadata", "links", "/rels/master", "invalid" )
					local cameraModel = KSTableUtils.derefOpt( docValue, "model" )

					if not localOnlyPath and not relsMaster then
						-- document originated from remote but binary is not yet available
						return
					end

					if isInvalid then
						-- Doc has been updated by remote but new binary has not been uploaded yet.
						-- Ignore for now.
						return
					end

					local incomingSha256 = KSTableUtils.derefOpt( docValue, "importSource", "sha256" )

					local localOnlySha256 = KSTableUtils.derefOpt( docValue, "_localOnly", "files", "presetProfile", "sha256" )

					local needsSave = incomingSha256 ~= localOnlySha256 -- will catch renames as well

					if needsSave then
						emit( cameraModel, incomingSha256, 1 )
					else
						emit( cameraModel, incomingSha256, 0 )
					end

				end

			end,

		}

		indexStoreSchema:addIndex [[CREATE INDEX presetsProfiles_cameraModel_needsSave ON presetsProfiles( cameraModel COLLATE NOCASE, needsSave )]]

	end

end

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

return LrmPresetsProfilesIndexDefinitions
