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

WFCatSearchByLocation.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 KSStringUtils = require 'KSStringUtils'
--------------------------------------------------------------------------------

local derefOpt = KSTableUtils.derefOpt

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


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

local WFCatSearchByLocation = {}

--[[
	Index definitions for finding assets by location.  The SQLite index only;
--]]
--------------------------------------------------------------------------------
local function addLocation( currentItemMap, requiredItemsList, item )
	if not item then
		return
	end
	
	item  = KSStringUtils.trim( item )
	if string.len( item ) == 0 then
		return
	end
	
	local itemLc =  string.lower( item )
	if not currentItemMap[ itemLc ] then
		currentItemMap[ itemLc ] = true
		table.insert( requiredItemsList, item )
	end
end
--------------------------------------------------------------------------------

function WFCatSearchByLocation.generateIndexSchema( indexStoreSchema )

	indexStoreSchema:addTable {

		sql = [[CREATE TABLE locations( location TEXT, lowerCaseLocation TEXT, isCatalogDocument )]],

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

		map = function( docValue, emit )

			local isSearchable, searchableDoc = isValidSearchableAssetDocument( docValue )
			if isSearchable and searchableDoc then
				
				local isCatalogDocument = derefOpt( searchableDoc, "_spaceId" ) and 0 or 1
				
				local requiredLocations = {}
				local currentValueMap = {}
				
				-- Ref links for the location fields documentation:
				-- http://apidocs.adbecrsl.com/v2/data-model/asset/location.html
				-- http://apidocs.adbecrsl.com/v2/data-model/asset/xmp.html
				
				local country = derefOpt( searchableDoc, 'xmp', 'photoshop', 'Country' )
				if country == nil then
					country = derefOpt( searchableDoc, 'location', 'country' )
				end
				
				local state = derefOpt( searchableDoc, 'xmp', 'photoshop', 'State' )
				if state == nil then
					state = derefOpt( searchableDoc, 'location', 'state' )
				end
				
				local city = derefOpt( searchableDoc, 'xmp', 'photoshop', 'City' )
				if city == nil then
					city = derefOpt( searchableDoc, 'location', 'city' )
				end
				
				addLocation( currentValueMap, requiredLocations, country )
				addLocation( currentValueMap, requiredLocations, state )
				addLocation( currentValueMap, requiredLocations, city )
				
				local subLocations = derefOpt( searchableDoc, 'location', 'sublocation' ) or {}
				for _, sublocation in ipairs( subLocations ) do
					addLocation( currentValueMap, requiredLocations, sublocation )
				end
				
				addLocation( currentValueMap, requiredLocations, derefOpt( searchableDoc, 'xmp', 'iptcCore', 'Location' ) )
				
				for _, location in ipairs( requiredLocations ) do
					
					local lowerCaseLocation = string.lower( location )
					emit( location, lowerCaseLocation, isCatalogDocument )
					
				end
			end

		end,

	}

	indexStoreSchema:addIndex
		[[CREATE INDEX locations_location ON locations( location, docId )]]

	indexStoreSchema:addIndex
		[[CREATE INDEX locations_lowerCaseLocation ON locations( lowerCaseLocation, location )]]

	indexStoreSchema:addIndex
		[[CREATE INDEX locations_isCatalogDocument ON locations( isCatalogDocument )]]

end

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

function WFCatSearchByLocation.addSearchToSearchSchema( searchSchema )

	searchSchema:addSearchableData {
		term = 'locations',
		dataType = 'locationsTerm',
		sql = [[SELECT docId FROM locations WHERE location = ?]],
		query_params = {
			'location',
		},
	}

end

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

function WFCatSearchByLocation.collectLocationDetailsOfRequiredAssets( wfCatalog, assetIds )
	
	return wfCatalog:indexStore():query {
		sql = [[SELECT DISTINCT location
                    FROM  TEMP_ids  
                    LEFT JOIN locations 
                    ON TEMP_ids.docId = locations.docId
                    ORDER BY lowerCaseLocation ASC]],
		tempIds = assetIds,
		calm = 5,
	}
	
end

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

function WFCatSearchByLocation.collectLocationDetailsOfAllAssets( wfCatalog )
	
	return wfCatalog:indexStore():query {
		sql = [[SELECT DISTINCT location
						FROM locations
						WHERE isCatalogDocument = 1
						ORDER BY lowerCaseLocation ASC]],
		calm = 5,
	}

end

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

return WFCatSearchByLocation
