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

WFCatSearchByImportDate.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 KSTableUtils = require 'KSTableUtils'
local WFCatSearchQuery = require 'WFCatSearchQuery'
local KSDate = require 'KSDate'
local NmbLRUCache = require 'NmbLRUCache'

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

local derefOpt = KSTableUtils.derefOpt

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


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

local WFCatSearchByImportDate = {}


local importTimeStringToPartsCache = NmbLRUCache.new( 20 )

--[[
	Index definitions for finding assets by date.  The SQLite index only;
		the table definition is shared (``asset`` table).
	Index definitions for identifying what years, months and days have assets.
	Queries for the above finding assets by date.
--]]

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

local function  interpretTimeDetails ( timeInStringFormat )

	if timeInStringFormat then
		local _, _, year, month, dayOfMonth, hour, minute, seconds = string.find( timeInStringFormat, 
			"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])T([0-9][0-9]):([0-9][0-9]):([0-9][0-9])" )

		if year and month and dayOfMonth then
			year, month, dayOfMonth, hour, minute, seconds
				= tonumber( year ), tonumber( month ) , tonumber( dayOfMonth ), tonumber( hour ), tonumber( minute ), tonumber( seconds )
			local combinedVal = seconds + minute * 100 + hour * 10000 + dayOfMonth * 1000000 + month * 100000000 + year * 10000000000
			if year and month and dayOfMonth then
				return year, month, dayOfMonth, hour, minute, seconds, combinedVal 
			end
		end
	end
end

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

function WFCatSearchByImportDate.generateIndexSchema( indexStoreSchema )


	indexStoreSchema:addTable {

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

		map = function( docValue, emit )
		
			local isSearchable, searchableDoc = isValidSearchableAssetDocument( docValue )
			
			local hasSpaceId = not not docValue._spaceId
			
			if isSearchable and searchableDoc and not hasSpaceId then
			
				local subType = docValue.subtype
				local importTime = derefOpt( searchableDoc, 'importSource', 'importTimestamp' )
				
				if not importTime then
					return
				end
				
				local year, month, dayOfMonth, hour, minute, seconds, combinedVal
				
				local maybeCacheValue = importTimeStringToPartsCache:get( importTime )
				if maybeCacheValue then
				
					year, month, dayOfMonth, hour, minute, seconds, combinedVal = unpack( maybeCacheValue )
				
				else
					
					-- ensure the importTimestamp is converted to UTC
					local importTimeAsUtc = KSDate.timeInIso8601Format( KSDate.iso8601ToTimeIntervalSinceReference( importTime ) )
					
					if importTimeAsUtc then
					
						year, month, dayOfMonth, hour, minute, seconds, combinedVal = interpretTimeDetails ( importTimeAsUtc )
						
						importTimeStringToPartsCache:set( importTime, { year, month, dayOfMonth, hour, minute, seconds, combinedVal } )
					
					else
						
						-- if the import time doesn't parse to UTC, then put it in the cache with empty parts
						-- so that we don't keep trying to calc the parts
						importTimeStringToPartsCache:set( importTime, {} )
					
					end
					
				end
				
				if year and month and dayOfMonth then
					
					emit( subType, year, month, dayOfMonth, hour, minute, seconds, combinedVal )
					
				end

			end

		end,

		useLocalId = true,
		hasOneRowPerDocument = true,

	}
		
	indexStoreSchema:addIndex
		[[CREATE INDEX importDate_complete ON importTime( completeTime, docId )]]
	
	indexStoreSchema:addIndex 
		[[CREATE INDEX importDate_completeTime_subType ON importTime( completeTime, subType )]]

end

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

function WFCatSearchByImportDate.importedDates( wfCatalog )

	return wfCatalog:indexStore():query( {

			sql =
				[[SELECT completeTime, count(completeTime) as CountOf 
				  FROM importTime 
				  WHERE subtype IN ( 'image', 'video' ) 
				  GROUP BY completeTime 
				  ORDER BY completeTime DESC LIMIT 10 ]],

			calm = WFCatSearchQuery.defaultQueryCalmRate 
		
		} )

end

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

function WFCatSearchByImportDate.addSearchToSearchSchema( searchSchema )
	
	searchSchema:addSearchableData {
		term = 'importTime',
		dataType = 'uint',
		query_params = {
			'time',
		},
		sql_table = 'importTime',
		column = 'completeTime',
	}
	
end

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

return WFCatSearchByImportDate
