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

WFCatSearchBySyncStatus.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2017 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 WFCatSyncStatus = require 'WFCatSyncStatus'
local NmbFileManagementSettings = require 'NmbFileManagementSettings'
local WFConfiguration = require 'WFConfiguration'

local SHOW_ORIGINALS_WERE_STORED_LOCALLY = WFConfiguration.FileManagement.showOldOriginalsStoredLocallyFilter

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

-- [anmurark 2018-01-25]: Any update in states need to be incorporated in LocalFilters_SyncStatus file as well
local kStatusFilterNeedsSyncing = "Syncing"
local kStatusFilterMarkedForOffline = "OriginalStoredLocally"
local kStatusFilterFullySynced = "Synced"
local kStatusFilterSyncedFromLrClassic = "SyncedFromLightromClassic"
local kStatusFilterErrorState = "Error"
local kStatusFilterMarkedForOffline_Old = "OriginalStoredLocally_Old"

local assetSyncStatusList = WFCatSyncStatus.getAssetSyncStatusList()

local kAssetSyncFilterToStatus = {}

-- Syncing States

kAssetSyncFilterToStatus[ kStatusFilterNeedsSyncing ] = { 
	assetSyncStatusList.NeedsMetadataUploaded, 
	assetSyncStatusList.NeedsOriginalUploaded,
	assetSyncStatusList.NeedsOriginalUploadedButOnOfflineVolume,
	assetSyncStatusList.NeedsOriginalDownloaded, 
	assetSyncStatusList.NeedsOriginalDownloadedForOffline, 
	assetSyncStatusList.NeedsProxyDownloadedForOffline, 
	assetSyncStatusList.NeedsProxyDownloaded, 
	assetSyncStatusList.NeedsDevelopXmpDownloaded, 
	assetSyncStatusList.NeedsOriginalDownloadToOfflineVolume, 
	assetSyncStatusList.NeedsProxyDownloadToOfflineVolume, 
	assetSyncStatusList.NeedsOriginalDownloadToOutOfSpaceVolume, 
	assetSyncStatusList.NeedsProxyDownloadToOutOfSpaceVolume,
	assetSyncStatusList.SyncPaused,
	assetSyncStatusList.SyncNoConnection,
	assetSyncStatusList.NeedsDevelopXmpUpload,
}


-- Marked-For-Offline / Stored Locally States

kAssetSyncFilterToStatus[ kStatusFilterMarkedForOffline ] = { 
	-- noop: We don't use the sync status table to filter
	-- these assets.
}

kAssetSyncFilterToStatus[ kStatusFilterMarkedForOffline_Old ] = { 
	-- noop: We don't use the sync status table to filter
	-- these assets.
}

-- Fully Synced and Backed Up States

kAssetSyncFilterToStatus[ kStatusFilterFullySynced ] = { 
	assetSyncStatusList.Completed,
	assetSyncStatusList.CompletedForOffline,
	assetSyncStatusList.OriginalIsOnOfflineVolume,
	assetSyncStatusList.ProxyIsOnOfflineVolume,
	assetSyncStatusList.NeedsOriginalMigration,
	assetSyncStatusList.NeedsProxyMigration
}

-- Synced from Lightroom Classic. Assets in this state have no
-- original in the cloud so it's not a part of the 
-- "Fully Synced and Backed Up" state.

kAssetSyncFilterToStatus[ kStatusFilterSyncedFromLrClassic ] = { 
	assetSyncStatusList.CompletedNoMaster,
}

-- Error States

kAssetSyncFilterToStatus[ kStatusFilterErrorState ] = { 
	assetSyncStatusList.StorageLimitExceeded, 
	assetSyncStatusList.InvalidLocalOriginal, 
	assetSyncStatusList.OriginalDownloadError, 
	assetSyncStatusList.ProxyDownloadError,
	assetSyncStatusList.DevelopXmpDownloadError,
	assetSyncStatusList.TrialOrSubscriptionExpired,
	assetSyncStatusList.InvalidAuxError,
}

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

local kAssetSyncStatusErrorFilters = {}

for _, statusId in ipairs( kAssetSyncFilterToStatus[ kStatusFilterErrorState ] ) do

	kAssetSyncStatusErrorFilters[ statusId ] = true

end

local kAssetSyncStatusLightroomClassicFilters = {}

for _, statusId in ipairs( kAssetSyncFilterToStatus[ kStatusFilterSyncedFromLrClassic ] ) do

	kAssetSyncStatusLightroomClassicFilters[ statusId ] = true

end

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

local function mapStatusIdToFilterString( rows )
	
	-- Some of the filters are static:
	
	local filters = {
	
		{ kStatusFilterNeedsSyncing },
		{ kStatusFilterFullySynced }
		
	}
	
	if not NmbFileManagementSettings.keepAllOriginals() then
	
		-- SPAM [jandrew 2018-01-25]: 
		-- Only show the "Original Stored Locally" filter if the user isn't keeping
		-- all originals local via the preferences. When the preferences is enabled,
		-- the option to mark individual assets to be stored locally is removed.
	
		table.insert( filters, { kStatusFilterMarkedForOffline } )
		
		if SHOW_ORIGINALS_WERE_STORED_LOCALLY then
			table.insert( filters, { kStatusFilterMarkedForOffline_Old } )
		end
		
	end
	
	-- The error and lr classic filters are dynamic:
	
	local addedErrorFilter = false
	local addedLrClassicFilter = false
	
	for _, row in ipairs( rows ) do
	
		local statusId = row[ 1 ]
		
		if statusId then
		
			if not addedErrorFilter and kAssetSyncStatusErrorFilters[ statusId ] then
			
				table.insert( filters, { kStatusFilterErrorState } )
				addedErrorFilter = true
				
			end
		
			if not addedLrClassicFilter and kAssetSyncStatusLightroomClassicFilters[ statusId ] then
				
				table.insert( filters, { kStatusFilterSyncedFromLrClassic } )
				addedLrClassicFilter = true
				
			end
		
			if addedErrorFilter and addedLrClassicFilter then
				break
			end
		
		end
		
	end

	return filters

end
--------------------------------------------------------------------------------

local WFCatSearchBySyncStatus = {}

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

function WFCatSearchBySyncStatus.getStatusIdsFromFilterValue( filterValue )
	
	return kAssetSyncFilterToStatus[ filterValue ] or {}
	
end

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

function WFCatSearchBySyncStatus.addSearchToSearchSchema( searchSchema )
	
	local keepLocallyConfiguration = WFCatSyncStatus.getKeepLocallyConfiguration()
	
	local sql =
			[[ SELECT docId FROM asset_sync_status_ui WHERE keepLocallyConfiguration == ]]
			.. keepLocallyConfiguration ..
			[[ AND prioritizedSyncStatus %OPERATOR %s ORDER BY docId]]
	
	searchSchema:addSearchableData {
		term = 'syncstatuses',
		dataType = 'syncStatusTerm',
		sql = sql,
		query_params = { 'syncstatus' }
	}
	
	searchSchema:addSearchableData {
		term = 'syncstatus',
		dataType = 'syncStatusTerm',
		sql = sql,
		query_params = { 'syncstatus' }
	}

end

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

function WFCatSearchBySyncStatus.collectSyncStatusDetailsOfRequiredAssets( wfCatalog, assetLocalIds )
	
	local keepLocallyConfiguration = WFCatSyncStatus.getKeepLocallyConfiguration()
	
	return wfCatalog:indexStore():query {
		sql = [[ SELECT DISTINCT asset_sync_status_ui.prioritizedSyncStatus
                    FROM CARRAY( ?, ?, 'int32' ) AS assetLocalIds
                    LEFT JOIN asset_sync_status_ui ON assetLocalIds.value == asset_sync_status_ui.docId
					WHERE keepLocallyConfiguration == ?
						AND asset_sync_status_ui.prioritizedSyncStatus IN ( ?, ?, ?, ?, ?, ?, ?, ? ) ]],
		assetLocalIds,
		#assetLocalIds,
		keepLocallyConfiguration,
		assetSyncStatusList.StorageLimitExceeded, 
		assetSyncStatusList.InvalidLocalOriginal, 
		assetSyncStatusList.OriginalDownloadError, 
		assetSyncStatusList.ProxyDownloadError,
		assetSyncStatusList.DevelopXmpDownloadError,
		assetSyncStatusList.TrialOrSubscriptionExpired,
		assetSyncStatusList.CompletedNoMaster,
		assetSyncStatusList.InvalidAuxError,
		calm = 5,
	}
	:map( mapStatusIdToFilterString )
	
end

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

function WFCatSearchBySyncStatus.collectSyncStatusDetailsOfAllAssets( wfCatalog )
	
	local keepLocallyConfiguration = WFCatSyncStatus.getKeepLocallyConfiguration()
	
	return wfCatalog:indexStore():query {
		sql = [[ SELECT DISTINCT prioritizedSyncStatus
					FROM asset_sync_status_ui
					WHERE keepLocallyConfiguration == ?
						AND prioritizedSyncStatus IN ( ?, ?, ?, ?, ?, ?, ?, ? ) ]],
		keepLocallyConfiguration,
		assetSyncStatusList.StorageLimitExceeded, 
		assetSyncStatusList.InvalidLocalOriginal, 
		assetSyncStatusList.OriginalDownloadError, 
		assetSyncStatusList.ProxyDownloadError,
		assetSyncStatusList.DevelopXmpDownloadError,
		assetSyncStatusList.TrialOrSubscriptionExpired,
		assetSyncStatusList.CompletedNoMaster,
		assetSyncStatusList.InvalidAuxError,
		calm = 5,
	}
	:map( mapStatusIdToFilterString )

end

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

function WFCatSearchBySyncStatus.isMarkedForOfflineFilter( syncFilterValue )

	return syncFilterValue == kStatusFilterMarkedForOffline

end

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

function WFCatSearchBySyncStatus.getMarkedForOfflineSql() 
	
	return [[ SELECT docId 
				FROM localStatusAndOzStatus
				WHERE isMarkedForOffline == 1
				ORDER BY docId ]]
	
end

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

function WFCatSearchBySyncStatus.isOldMarkedForOfflineFilter( syncFilterValue )

	return syncFilterValue == kStatusFilterMarkedForOffline_Old

end

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

function WFCatSearchBySyncStatus.getOldMarkedForOfflineSql() 
	
	return [[ SELECT docId 
				FROM localStatusAndOzStatus
				WHERE oldIsMarkedForOffline == 1
				ORDER BY docId ]]
	
end

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

function WFCatSearchBySyncStatus.completeNoErrorSyncStatus( )
	
	return kStatusFilterFullySynced

end


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

return WFCatSearchBySyncStatus
