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

WFCatStyleBinaryDownloaderTest.lua

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

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.

------------------------------------------------------------------------------]]
	-- Rx
local Rx = require 'Rx'

	-- WF.core.lua
local KSData = require 'KSData'
local KSIdGenerator = require 'KSIdGenerator'
local KSPathUtils = require 'KSPathUtils'
local WFFileUtls = require 'WFFileUtils'

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

	-- WF.oz_client.managed_catalog
local WFCatStyleBinaryDownloader = require 'WFCatStyleBinaryDownloader'
local WFCatSpecMock = require 'WFCatSpecMock'
local WFCatMockCatalog = require 'WFCatMockCatalog'

local WFRxHttpClient = require 'WFRxHttpClient'

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

local kUserId = '87f526b44f9e41eca6cb5a550f84ceb6'
	-- Helpful bash one-liner. Put a new uuid on the clipboard (mac cmdline):
	-- uuidgen	| perl -p -e 's/-//g;s/[A-Z]/lc($&)/ge;' | pbcopy

local priority = WFRxHttpClient.requestPriorityLow
local cost = WFRxHttpClient.requestCostDefault

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

local WFCatStyleBinaryDownloaderTest = {}

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

local function makeSuccessfulResponseHeaders( response )

	return {
		status_code = '200',
		[ 'Content-Length' ] = KSData.length( response ),
	}

end

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

local function makeUrlResponse( url, responseString, maybeCost )

	local response = KSData.make( responseString )

	return {
		url = url,
		response = response,
		headers = makeSuccessfulResponseHeaders( response ),
		options = {
			requestCost = maybeCost or cost,
			requestPriority = priority,
			followRedirects = true,
			requestHeaders = {
				{
					header = "Prefer",
					value = "download-direct",
				},
			}
		}
	}

end

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

local function pack( ... )

	return { ... }

end

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

local function matchesAssetRequest( assetId )

	return function( responseAssetId )

		return responseAssetId == assetId

	end

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

local function makeResponseStreamForRequest( downloader, assetId )

	return downloader:getResponseStream()
		:where( matchesAssetRequest( assetId ) )
		:take( 1 )
end
--------------------------------------------------------------------------------

local function doOneDownload( downloader, assetId )

	local savedSubscription
	
	return Rx.Observable.create(
		function( observer )

			local responseStream = makeResponseStreamForRequest( downloader, assetId )
			
			savedSubscription = 
					responseStream:subscribe( observer )

			downloader:requestStyleBinary( assetId )
			
			return Rx.Disposable.create( function()

					-- TODO [ashj 2018-03-09]: When the stream is
					-- complete, this will get call. Can we
					-- differentiate?
					
					downloader:cancelStyleBinaryRequest( assetId )
					savedSubscription:dispose()

			end )
		
	end )
end

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

local function ensureStyleDestinationFolderExistsfor( catalog )

	-- Make sure that the parent folder exists.
	-- Finding it using a dummy path.
	
	local dummyCameraProfilePath = catalog:fileSpec():pathForDCP( "Dummy.dcp" )
	local dummyPresetPath = catalog:fileSpec():pathForStyle( "6f607906eefa4e9fb80da8fde2805c11" )

	WFFileUtls.mkdir( KSPathUtils.parent( dummyCameraProfilePath ))
	WFFileUtls.mkdir( KSPathUtils.parent( dummyPresetPath ))
end

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

function WFCatStyleBinaryDownloaderTest.rxTestGetStyleBinary( rxTest )

	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/v2/catalogs/blah/blah/master", "pseudo-master" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = "6f607906eefa4e9fb80da8fde2805c11"

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForStyle( assetId )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	local data = KSData.memoryMappedContentsOfFile( path )
	rxTest:expectSingleValue(

		Rx.Observable.just( tostring( data ) ),

		"pseudo-master" )
	
	data:close()
	
end

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

function WFCatStyleBinaryDownloaderTest.rxTestGetStyleBinaryHttpError( rxTest )

	local errorMessage = "Not found"
	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			{
				url = "/v2/catalogs/blah/blah/master",
				fail = {
					errorMessage,
					headers = {
						status_code = '404',
					},
				},
				options = {
					requestCost = cost,
					requestPriority = priority,
					followRedirects = true,
					requestHeaders = {
						{
							header = "Prefer",
							value = "download-direct",
						},
					}
				}
			},
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = '6f607906eefa4e9fb80da8fde2805c11'

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
		},

		':ignore:' )
	
	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, false, errorMessage } )

end


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

function WFCatStyleBinaryDownloaderTest.rxTestGetCameraProfileBinary( rxTest )

	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/v2/catalogs/blah/blah/master", "pseudo-master" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = "6f607906eefa4e9fb80da8fde2805c11"
	local fileName = "Dummy profile.dcp" 

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			subtype = "camera_profile",
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
			
			fileName = fileName,
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForDCP( fileName )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	local data = KSData.memoryMappedContentsOfFile( path )
	rxTest:expectSingleValue(

		Rx.Observable.just( tostring( data ) ),

		"pseudo-master" )
	
	data:close()

end

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

function WFCatStyleBinaryDownloaderTest.rxTestGetStyleBinaryDownloadAgain( rxTest )

	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/v2/catalogs/blah/blah/master", "pseudo-master" ),
			makeUrlResponse( "/v2/catalogs/blah/blah/master2", "pseudo-master2" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = "6f607906eefa4e9fb80da8fde2805c11"

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForStyle( assetId )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	local data = KSData.memoryMappedContentsOfFile( path )
	rxTest:expectSingleValue(

		Rx.Observable.just( tostring( data ) ),

		"pseudo-master" )
	
	data:close()
	
	-- Now change the asset master and try downloading again
	
	rxTest:expectSingleValue(

		catalog:docStore():applyOverlay {
			_id = assetId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master2',
					},
				},
			},
		},

		':ignore:' )
		
	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	data = KSData.memoryMappedContentsOfFile( path )
	rxTest:expectSingleValue(

		Rx.Observable.just( tostring( data ) ),

		"pseudo-master2" )
	
	data:close()
end

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

function WFCatStyleBinaryDownloaderTest.rxTestGetCameraProfileBinarySameFileName( rxTest )

	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/v2/catalogs/blah/blah/master", "pseudo-master" ),
			makeUrlResponse( "/v2/catalogs/blah/blah/master2", "pseudo-master2" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = "6f607906eefa4e9fb80da8fde2805c11"
	local fileName = "Dummy profile.dcp" 

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			subtype = "camera_profile",
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
			
			fileName = fileName,
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForDCP( fileName )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	-- Download another camera profile with the same
	-- file name
	local assetId2 = KSIdGenerator.uuidInLowercaseHex()
	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId2,
			subtype = "camera_profile",
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master2',
					},
				},
			},
			
			fileName = fileName,
		},

		':ignore:' )
	
	local assetId2Path = KSPathUtils.child( KSPathUtils.parent( path ), "Dummy profile-2.dcp" )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId2 )
			:map( pack ),

		{ assetId2, true, assetId2Path } )
	

end

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

function WFCatStyleBinaryDownloaderTest.rxTestGetCameraProfileBinaryDownloadAgain( rxTest )

	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/v2/catalogs/blah/blah/master", "pseudo-master" ),
			makeUrlResponse( "/v2/catalogs/blah/blah/master2", "pseudo-master2" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensureStyleDestinationFolderExistsfor( catalog )

	local downloader = WFCatStyleBinaryDownloader( catalog )
	local assetId = "6f607906eefa4e9fb80da8fde2805c11"
	local fileName = "Dummy profile.dcp" 

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = assetId,
			subtype = "camera_profile",
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master',
					},
				},
			},
			
			fileName = fileName,
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForDCP( fileName )

	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	
	
	-- Download again for the same asset
	
	rxTest:expectSingleValue(

		catalog:docStore():applyOverlay {
			_id = assetId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/master' ] = {
						href = '/v2/catalogs/blah/blah/master2',
					},
				},
			},
			
			fileName = fileName,
		},

		':ignore:' )
	
	rxTest:expectSingleValue(

		doOneDownload( downloader, assetId )
			:map( pack ),

		{ assetId, true, path } )
	

end

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

return WFRxTestCase.wrapSuite( 'WFCatStyleBinaryDownloaderTest', WFCatStyleBinaryDownloaderTest )
