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

ADOBE CONFIDENTIAL
------------------
Copyright 2022 Adobe Inc.
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.

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

-- WF.core.self_test
local WFRxTestCase = require 'WFRxTestCase'

	-- Utilities
local KSTableUtils = require "KSTableUtils"
local KSPathUtils = require "KSPathUtils"
local WFFileUtils = require "WFFileUtils"
local WFRxDocStore = require "WFRxDocStore"
local WFCatalogTestUtils = require "WFCatalogTestUtils"
local WFRxIndexStoreSchemaVersionList = require "WFRxIndexStoreSchemaVersionList"

local WFCatFileConductorConstants = require "WFCatFileConductorConstants"

local LraMigrateCacheModel = require "LraMigrateCacheModel"

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

local derefOpt = KSTableUtils.derefOpt

local LraMigrateCacheModelTest = {}

-- TODO [immisch] 2022-03-14: This is the schemaVersionList that matches the currently shipping version as of today,
-- but this may have to be updated

local indexStoreSchemaVersionList = {
	{
		sequence = 0, -- wf/releases/3.3
	},
	{
		sequence = 1,
		platforms = { "Desktop", },
		tables = { "asset_sync_status_ui", "assetPathsAndInfo", "presetsAndProfiles" }
		-- https://git.corp.adobe.com/lua/wf/pull/3290/commits/2cfc47bd4caf3b88c0d6d04a7db5ffe69a0b3ca5
		-- https://git.corp.adobe.com/lua/wf/pull/3290/commits/dc44a83f7f56d0e276505e4f0963e53b419215ae
	},
	{
		sequence = 2,
		platforms = { "Mobile", },
		tables = { "album_asset", "albums", "blocked_uploads", "cacheReferences", "profileRegistration",
					"presetsProfiles", "trashAssets" }
		-- https://git.corp.adobe.com/lua/wf/pull/3290/commits/dc44a83f7f56d0e276505e4f0963e53b419215ae
	},
	{
		sequence = 3,
		platforms = { "Android", },
		tables = { "CustomCameraProfiles", "coreMD5" }
		-- https://git.corp.adobe.com/lua/wf/pull/3290/commits/dc44a83f7f56d0e276505e4f0963e53b419215ae
	},
	{
		sequence = 4,
		platforms = { "All", },
		tables = { "space_album" }
		-- https://git.corp.adobe.com/lua/wf/pull/3290/commits/dc44a83f7f56d0e276505e4f0963e53b419215ae
	},
	{
		sequence = 5,
		platforms = { "Desktop", },
		tables = { "cameras", "keywords", "locations" }
		-- https://git.corp.adobe.com/lua/wf/pull/3332/commits/0cdb2163bd6b84d140b751eb3b2c735c49caabe2
	},
	{
		sequence = 6,
		platforms = { "Desktop", },
		tables = { "asset_sync_status_ui" }
		-- https://git.corp.adobe.com/lua/wf/pull/3358/commits/9b5220328caddc5eb38e03bd13a674f6f25e2cb2
	},
	{
		sequence = 7,
		platforms = { "Mobile", },
		tables = { "coreInfo" }
		-- https://git.corp.adobe.com/lua/wf/pull/3358/commits/9b5220328caddc5eb38e03bd13a674f6f25e2cb2
	},
	{
		sequence = 8,
		platforms = { "All", },
		tables = { "needsBinaryUpload" }
		-- https://git.corp.adobe.com/lua/wf/pull/3379
	},
	{
		sequence = 9,
		platforms = { "Android", },
		tables = { "cacheReferences", "trashAssets" }
		-- https://git.corp.adobe.com/lua/wf/pull/3389
	},
	{
		sequence = 11,
		platforms = { "Desktop", },
		tables = { "simple_updates" }
		-- https://jira.corp.adobe.com/browse/WF-1730
	}
}

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

local function verifyDocument( rxTest, docValue, catalogPath )

	-- This tests renditions and xmp_develop, but it does not test that originals are moved
	-- correctly, because for those, absolute paths were used

	local found = 0

	for _, layoutInfo in pairs( WFCatFileConductorConstants.layoutConventions ) do

		if type(layoutInfo ) == 'table' then
			local fileInfo = derefOpt( docValue, unpack( layoutInfo.localOnly ) )
			if fileInfo and fileInfo.relativePath then

				local absPath = KSPathUtils.child( catalogPath, fileInfo.relativePath )

				local attrs = WFFileUtils.fileAttributes( absPath )
				rxTest:expectEqual( true, not not attrs )
				rxTest:expectEqual( fileInfo.fileSize, attrs.fileSize )

				found = found + 1
			end
		end

	end

	rxTest:expectEqual( true, found > 0 )
end

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

function LraMigrateCacheModelTest.rxTestMigrate_testNightly( rxTest )

	rxTest:setTimeLimit( 1200 )

	WFRxIndexStoreSchemaVersionList.TEST_setSchemaVersionList( rxTest, indexStoreSchemaVersionList )

	local catalogId = 'ee47bf5197544783b9e2f7948c1e6aee'

    local documentsDir = KSPathUtils.getStandardFilePath 'carouselDocuments'
    local catalogPath =  KSPathUtils.child( documentsDir, catalogId )

	-- clean up from previous test runs
	WFFileUtils.delete( catalogPath )
	WFFileUtils.mkdir( catalogPath )

	local files = {
		'Managed Catalog.mcat',
		'Managed Catalog.wfindex',
		'renditions/previewCache',
		'Originals/2020/2020-04/IMG_4459_proxy.dng',
		'xmp_develop/8bb6e65096a41f9ced84c101c27d1136a237a94ad13c83af912be6a5d748bdda.rdf'
	}

	local artifactoryBase = "https://artifactory-sj1.corp.adobe.com/artifactory/generic-wf-testing/TestingCatalogs/androidPreviewCache"

	local androidPreviewCacheDir = KSPathUtils.child(
		KSPathUtils.child(
			KSPathUtils.getStandardFilePath( 'home' ), '.wfTestingCatalogs' ), 'androidPrewiewCache' )

	-- download/copy all files
	for _, file in ipairs( files ) do
		local dest = KSPathUtils.child( catalogPath, file )
		local destDir = KSPathUtils.parent( dest )
		if not WFFileUtils.exists( destDir ) then
			WFFileUtils.mkdir( destDir )
		end

		local cachedCopy = KSPathUtils.child( androidPreviewCacheDir, file )
		if WFFileUtils.exists( cachedCopy ) then
			WFFileUtils.deleteFile( dest )
			WFFileUtils.copy( cachedCopy, dest )
		else
			local url = KSPathUtils.child( artifactoryBase, file )

			rxTest:waitFor( WFCatalogTestUtils.getFileFromArtifactory( url, dest) )
		end
		rxTest:finally( function()
			WFFileUtils.deleteFile( dest )
		end )
	end

	local model = LraMigrateCacheModel.makeModel( catalogPath, catalogId, 'f9e358e68b7137a5d48d66b6e20f2d7a' )

	local TEST_migratedDocs

	local obs = rxTest:observe(  model.value
		:map(function( result )
			if result.TEST_migratedDocs then
				TEST_migratedDocs = result.TEST_migratedDocs
				result.TEST_migratedDocs = nil
			end

			-- map away fields we aren't interested in
			if result.progress then
				result.progress.description = nil
				result.progress.errorCount = nil
				result.progress.percentComplete = nil
			end

			return result
		end ) )

	obs:expectData( {
		progress = { processedCount = 0, totalCount = 113 }
	} )

	obs:expectData( {
		progress = { processedCount = 50, totalCount = 113 }
	} )

	obs:expectData( {
		progress = { processedCount = 100, totalCount = 113 }
	} )

	obs:expectData( {
		progress = { processedCount = 113, totalCount = 113 }
	} )

	obs:expectData( {
		result = 113
	} )

	obs:expectCompleted()

	local docStore = WFRxDocStore( KSPathUtils.child( catalogPath, 'Managed Catalog.mcat' ) )

	local verifyFiles = docStore:bulkDocValue( TEST_migratedDocs )
		:map( function( docs )

			for _, doc in pairs( docs ) do

				verifyDocument( rxTest, doc, catalogPath )

			end
			return #docs
		end )
		:sum()

	rxTest:expectSingleValue( verifyFiles, 113 )

	rxTest:expectOnlyCompleted( docStore:halt() )

end

return WFRxTestCase.wrapSuite( 'LraMigrateCacheModelTest', LraMigrateCacheModelTest )
