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

WFCatSortByModifiedTime.lua

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

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

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

local WFCatSortByModifiedTime = {}
local KSTableUtils = require 'KSTableUtils'
local KSDate = require 'KSDate'

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

local derefOpt = KSTableUtils.derefOpt

local isValidSearchableAssetDocument = assert( require 'WFCatIndexUtils'.isValidSearchableAssetDocument )


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

function WFCatSortByModifiedTime.executeSort( wfCatalog, assetLocalIds, order )
		
		if order ~= "ASC" then
			order = "DESC"
		end
		
		local sqlString = string.format(
			[[ SELECT modifiedTime.docId, modifiedTime.completeTime
				FROM CARRAY( ?, ?, 'int32' ) AS assetLocalIds
				LEFT JOIN modifiedTime ON modifiedTime.docId = assetLocalIds.value
				LEFT JOIN assets ON assets.docId = assetLocalIds.value
				ORDER BY modifiedTime.completeTime %s,
						assets.captureDate %s,
						assets.filenameLC COLLATE i18n_collate %s,
						modifiedTime.docId %s ]],
				order, order, order, order )

		return wfCatalog:indexStore():query( {
	
			sql = sqlString,
			calm = 1,
			assetLocalIds,
			#assetLocalIds

		})
		
end

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

function WFCatSortByModifiedTime.generateIndexSchema( indexStoreSchema )

	indexStoreSchema:addTable {

		sql = [[CREATE TABLE modifiedTime( year, month, dayOfMonth, hour, minute, completeTime )]],
		
		relevantTypeSubtypeTuples = {
			{ 'asset', '*' }
		},

		map = function( docValue, emit )
			
			local isSearchable, searchableDoc = isValidSearchableAssetDocument( docValue )
			
			if isSearchable and searchableDoc then

				local userUpdated = derefOpt( searchableDoc, 'userUpdated' )
				
				if not userUpdated then
			
					userUpdated = userUpdated or derefOpt( docValue, 'captureDate' )
				
				end
				
				local userUpdatedDateAsTimeInterval
				
				local success
				
				if userUpdated == '0000-00-00T00:00:00' then
					
					-- iso8601ToTimeIntervalSinceReference failes on the Zero-date, so use
					-- use a very old default time interval that should come before any
					-- provided capture date.
					
					success = true
					userUpdatedDateAsTimeInterval = -10000000000

				elseif userUpdated then
				
					success, userUpdatedDateAsTimeInterval = pcall( KSDate.iso8601ToTimeIntervalSinceReference, userUpdated )
					
				end
				
				local year, month, dayOfMonth, hour, minute
				
				if success then
					success, year, month, dayOfMonth, hour, minute = pcall( KSDate.getDecomposedTime, userUpdatedDateAsTimeInterval )
				end
				
				if success and year and month and dayOfMonth then
					emit( year, month, dayOfMonth, hour, minute, userUpdatedDateAsTimeInterval )
				end

			end

		end,

		useLocalId = true,
		hasOneRowPerDocument = true,

	}
		
	indexStoreSchema:addIndex
		[[CREATE INDEX modifiedTime_complete ON modifiedTime( completeTime, docId )]]

end


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

return WFCatSortByModifiedTime
