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

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.NeedsOriginalProxyToOutOfSpaceVolume,
	assetSyncStatusList.SyncPaused,
	assetSyncStatusList.SyncNoConnection,
}


-- 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
}

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

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 syncStatusColumnName = WFCatSyncStatus.getSyncStatusColumnName()
	
	local sql = [[SELECT docId FROM asset_sync_status_ui WHERE ]] .. syncStatusColumnName .. [[ %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, assetIds )
	
	local syncStatusColumnName = WFCatSyncStatus.getSyncStatusColumnName()
	
	return wfCatalog:indexStore():query {
		sql = string.format( [[ SELECT DISTINCT asset_sync_status_ui.%s
                    FROM  TEMP_ids
                    LEFT JOIN asset_sync_status_ui 
                    	ON TEMP_ids.docId = asset_sync_status_ui.docId
					WHERE asset_sync_status_ui.%s IN ( ?, ?, ?, ?, ?, ?, ? ) ]],
					syncStatusColumnName, syncStatusColumnName ),
		assetSyncStatusList.StorageLimitExceeded, 
		assetSyncStatusList.InvalidLocalOriginal, 
		assetSyncStatusList.OriginalDownloadError, 
		assetSyncStatusList.ProxyDownloadError,
		assetSyncStatusList.DevelopXmpDownloadError,
		assetSyncStatusList.TrialOrSubscriptionExpired,
		assetSyncStatusList.CompletedNoMaster,
		tempIds = assetIds,
		calm = 5,
	}
	:map( mapStatusIdToFilterString )
	
end

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

function WFCatSearchBySyncStatus.collectSyncStatusDetailsOfAllAssets( wfCatalog )
	
	local syncStatusColumnName = WFCatSyncStatus.getSyncStatusColumnName()
	
	return wfCatalog:indexStore():query {
		sql = string.format( [[ SELECT DISTINCT %s
					FROM asset_sync_status_ui
					WHERE %s IN ( ?, ?, ?, ?, ?, ?, ? ) ]], 
					syncStatusColumnName, syncStatusColumnName ),
		assetSyncStatusList.StorageLimitExceeded, 
		assetSyncStatusList.InvalidLocalOriginal, 
		assetSyncStatusList.OriginalDownloadError, 
		assetSyncStatusList.ProxyDownloadError,
		assetSyncStatusList.DevelopXmpDownloadError,
		assetSyncStatusList.TrialOrSubscriptionExpired,
		assetSyncStatusList.CompletedNoMaster,
		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
