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

ADOBE CONFIDENTIAL
------------------
Copyright 2018 Adobe Systems Incorporated
All Rights Reserved.

NOTICE: All information contained herein is, and remain 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 may be covered by U.S. and Foreign
Patents, patents in process, and are protected by trade secret or copyright
law.  Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

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

	-- RxLua
local Rx = require 'Rx'

	-- WF.core.self_test
local WFRxTestCase = require 'WFRxTestCase'
	-- WF.oz_client.catalog
local OzCatalogUrls = require 'OzCatalogUrls'
	-- WF.core.os
local KSPathUtils = require 'KSPathUtils'

	-- WF.oz_client.managed_catalog.sync_engine
local WFCatUser = require 'WFCatUser'
local WFCatSpec = require 'WFCatSpec'
local WFCatalog = require 'WFCatalog'

	-- WF.core.utils
local KSIdGenerator = require 'KSIdGenerator'
local KSTableUtils = require 'KSTableUtils'

	-- WF.oz_client.managed_catalog
local WFCatTrash = require 'WFCatTrash'

	-- WF.oz_client.docstore
local OzCatalogServiceViaWFCatalog = require 'OzCatalogServiceViaWFCatalog'

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

local derefOpt = KSTableUtils.derefOpt

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

local LrmLibraryDeleteTest = {}

local kUser1 = string.rep( '1', 32 )
local kCatalogId = string.rep( 'c', 32 )

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

local function mockCatalogSetUp( rxTest)

	local catUser, wfCatalogStream
	local wfCatalog, catalog

	local userInfoCachePath = ':memory:'
	local userId = kUser1
	local serverBaseUrl = OzCatalogUrls.baseServerUrl
	local rootCatalogPath = KSPathUtils.getStandardFilePath 'temp'
	
	local catalogOptions = {
		indexSpecScript = 'LrmCatalogIndexDefinitions.lua',
		setupConflictResolver = false,
		docStorePath = ':memory:',
	}
	
	catUser = WFCatUser( serverBaseUrl, userId, userInfoCachePath )
	
	local catSpec = WFCatSpec( catUser, kCatalogId )
	wfCatalog = WFCatalog( catSpec, rootCatalogPath, catalogOptions )
	
	wfCatalogStream = Rx.Observable.just( wfCatalog )
	
	catalog = OzCatalogServiceViaWFCatalog( wfCatalogStream )

	rxTest:finally( function()
		wfCatalog:close()
		catUser:close()
		catalog:close()
	end )

	return catalog, wfCatalog

end

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

function LrmLibraryDeleteTest.rxTestMoveAssetToTrash( rxTest )

	local catalog, wfCatalog = mockCatalogSetUp( rxTest )

	local assetId = KSIdGenerator.uuidInLowercaseHex()
	local localUrl = KSIdGenerator.uuid()
	
	rxTest:setTimeLimit( 10 )

	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			subtype = 'image',
			_id = assetId,
			importSource = {
				originalWidth = 30,
				originalHeight = 20,
			},
			captureDate = '2012-08-15T15:22:29',
			_localOnly = {
				files = {
					thumbnail2x = {
						path = 'blobs/...',
					},
					preview = {
						path = 'blobs/...',
					}
				},
				localUrl = localUrl,
			},
		},
		':ignore:'
	)
	
	local observeCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT docId FROM coreInfo ]]
		})
		
	local observeTrashCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT COUNT(*) FROM trashAssets ]]
		})
		
	observeCoreInfo:expectData { { assetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	local assetIds = { assetId }
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.moveAssetsToTrash( wfCatalog, assetIds )
	)

	observeCoreInfo:expectData{}
	observeTrashCoreInfo:expectData { { 1 } }
	
	
	local trashAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM trashAssets ]]
		}
		:map( function( row ) 
			trashAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	rxTest:expectSingleValue(
		catalog:docStore():docValue( trashAssetId )
			:pluck( 'original', 'id' ),
		assetId
	)
	
end

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

function LrmLibraryDeleteTest.rxTestDeleteTrashAsset( rxTest )

	local catalog, wfCatalog = mockCatalogSetUp( rxTest )

	local assetId = KSIdGenerator.uuidInLowercaseHex()
	local localUrl = KSIdGenerator.uuid()
	
	rxTest:setTimeLimit( 10 )

	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			subtype = 'image',
			_id = assetId,
			importSource = {
				originalWidth = 30,
				originalHeight = 20,
			},
			captureDate = '2012-08-15T15:22:29',
			_localOnly = {
				files = {
					thumbnail2x = {
						path = 'blobs/...',
					},
					preview = {
						path = 'blobs/...',
					}
				},
				localUrl = localUrl,
			},
		},
		':ignore:'
	)
	
	local observeCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT docId FROM coreInfo ]]
		})
		
	local observeTrashCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT COUNT(*) FROM trashAssets ]]
		})
		
	observeCoreInfo:expectData { { assetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	local assetIds = { assetId }
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.moveAssetsToTrash( wfCatalog, assetIds )
	)

	observeCoreInfo:expectData {}
	observeTrashCoreInfo:expectData { { 1 } }
	
	local trashAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM trashAssets ]]
		}
		:map( function( row ) 
			trashAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.deleteTrashAssets( wfCatalog, {trashAssetId} )
	)
	
	observeTrashCoreInfo:expectData { { 0 } }
	
end

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

function LrmLibraryDeleteTest.rxTestDirectlyDeleteAsset( rxTest )

	local catalog, wfCatalog = mockCatalogSetUp( rxTest )

	local assetId = KSIdGenerator.uuidInLowercaseHex()
	local localUrl = KSIdGenerator.uuid()
	
	rxTest:setTimeLimit( 10 )

	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			subtype = 'image',
			_id = assetId,
			importSource = {
				originalWidth = 30,
				originalHeight = 20,
			},
			captureDate = '2012-08-15T15:22:29',
			_localOnly = {
				files = {
					thumbnail2x = {
						path = 'blobs/...',
					},
					preview = {
						path = 'blobs/...',
					}
				},
				localUrl = localUrl,
			},
		},
		':ignore:'
	)
	
	local observeCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT docId FROM coreInfo ]]
		})
		
	local observeTrashCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT COUNT(*) FROM trashAssets ]]
		})
		
	observeCoreInfo:expectData { { assetId } }
	
	local assetIds = { assetId }
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.directlyDeleteAssets( wfCatalog, assetIds )
	)

	observeCoreInfo:expectData {}
	observeTrashCoreInfo:expectData { { 0 } }
	
end

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

function LrmLibraryDeleteTest.rxTestRestoreTrashAsset_fromSyncedTrash( rxTest )

	local catalog, wfCatalog = mockCatalogSetUp( rxTest )

	local assetId = KSIdGenerator.uuidInLowercaseHex()
	local localUrl = KSIdGenerator.uuid()
	
	rxTest:setTimeLimit( 10 )

	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			subtype = 'image',
			_id = assetId,
			importSource = {
				originalWidth = 30,
				originalHeight = 20,
			},
			captureDate = '2012-08-15T15:22:29',
			_localOnly = {
				files = {
					thumbnail2x = {
						path = 'blobs/...',
					},
					preview = {
						path = 'blobs/...',
					}
				},
				localUrl = localUrl,
			},
		},
		':ignore:'
	)
	
	local observeCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT docId FROM coreInfo ]]
		})
		
	local observeTrashCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT COUNT(*) FROM trashAssets ]]
		})
		
	observeCoreInfo:expectData { { assetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	local assetIds = { assetId }

	rxTest:expectOnlyCompleted (
		WFCatTrash.moveAssetsToTrash( wfCatalog, assetIds )
	)

	observeCoreInfo:expectData {}
	observeTrashCoreInfo:expectData { { 1 } }
	
	local trashAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM trashAssets ]]
		}
		:map( function( row ) 
			trashAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			_id = trashAssetId,
			_serverProvidedMetadata = {},
		},
		':ignore:'
	)
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.restoreTrashAssets( wfCatalog, { trashAssetId } )
	)
	
	local restoredAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM coreInfo ]],
			quiesceUntilUpToDate = true
		}
		:map( function( row ) 
			restoredAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	observeCoreInfo:expectData { { restoredAssetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	rxTest:expectSingleValue ( 
		catalog:docStore():docValue( restoredAssetId )
		:map( function( docValue ) 
			return derefOpt( docValue, '_localOnly', 'universal', 'trash', 'createFrom', 'id' ) == trashAssetId
		end )
		:take(1)
		, true
	)
	
end

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

function LrmLibraryDeleteTest.rxTestRestoreTrashAsset_fromSyncedOriginal( rxTest )

	local catalog, wfCatalog = mockCatalogSetUp( rxTest )

	local assetId = KSIdGenerator.uuidInLowercaseHex()
	local localUrl = KSIdGenerator.uuid()
	
	rxTest:setTimeLimit( 10 )

	rxTest:expectSingleValue ( 
		catalog:docStore():applyOverlay {
			type = 'asset',
			subtype = 'image',
			_id = assetId,
			importSource = {
				originalWidth = 30,
				originalHeight = 20,
			},
			captureDate = '2012-08-15T15:22:29',
			_localOnly = {
				files = {
					thumbnail2x = {
						path = 'blobs/...',
					},
					preview = {
						path = 'blobs/...',
					}
				},
				localUrl = localUrl,
			},
			_serverProvidedMetadata = {}
		},
		':ignore:'
	)
	
	local observeCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT docId FROM coreInfo ]]
		})
		
	local observeTrashCoreInfo = rxTest
		:observe( catalog:indexStore():query{
			sql = [[SELECT COUNT(*) FROM trashAssets ]]
		})
		
	observeCoreInfo:expectData { { assetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	local assetIds = { assetId }
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.moveAssetsToTrash( wfCatalog, assetIds )
	)

	observeCoreInfo:expectData {}
	observeTrashCoreInfo:expectData { { 1 } }
	
	local trashAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM trashAssets ]]
		}
		:map( function( row ) 
			trashAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	rxTest:expectOnlyCompleted ( 
		WFCatTrash.restoreTrashAssets( wfCatalog, { trashAssetId } )
	)
	
	local restoredAssetId
	
	rxTest:expectSingleValue ( 
		catalog:indexStore():query {
			sql = [[SELECT docId FROM coreInfo ]],
			quiesceUntilUpToDate = true
		}
		:map( function( row ) 
			restoredAssetId = row[1] and row[1][1]
			return {}
		end )
		:take(1)
		, {}
	)
	
	observeCoreInfo:expectData { { restoredAssetId } }
	observeTrashCoreInfo:expectData { { 0 } }
	
	rxTest:expectSingleValue ( 
		catalog:docStore():docValue( restoredAssetId )
		:map( function( docValue ) 
			-- createFrom indicates the id of the asset currently on oz.  MetadataPusher will
			-- see this is the same subtype as the restored id ona inject a temporary trash
			-- asset to satisfy oz only being able to restore from a trash asset.
			return derefOpt( docValue, '_localOnly', 'universal', 'trash', 'createFrom', 'id' ) == assetId
		end )
		:take(1)
		, true
	)
	
end

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

if require 'WFPlatformInfo'.isDesktop then return {} end

return WFRxTestCase.wrapSuite( LrmLibraryDeleteTest )
