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

WFCatPersonBinaryDownloaderTest.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 KSPathUtils = require 'KSPathUtils'
local WFFileUtls = require 'WFFileUtils'

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

	-- WF.oz_client.managed_catalog
local WFCatPersonBinaryDownloader = require 'WFCatPersonBinaryDownloader'
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.requestPriorityHigh
local cost = WFRxHttpClient.requestCostDownloadRendition

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

local WFCatPersonBinaryDownloaderTest = {}

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

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

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

local function pack( ... )

	return { ... }

end

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

local function matchesPersonRequest( personId )
	return function( responsePersonId )
		return responsePersonId == personId
	end
end
--------------------------------------------------------------------------------

local function makeResponseStreamForRequest( downloader, personId )

	return downloader:getResponseStream()
		:where( matchesPersonRequest( personId ) )
		:take( 1 )
end
--------------------------------------------------------------------------------

local function doOneDownload( downloader, personId )

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

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

			downloader:requestPersonBinary( personId, personId )
			
			return Rx.Disposable.create( function()
					
					downloader:cancelPersonBinaryRequest( personId )
					savedSubscription:dispose()

			end )
	end )
end

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

local function ensurePersonDestinationFolderExistsfor( catalog, personId )
	local dummyPersonPath = catalog:fileSpec():pathForPerson( personId )
	WFFileUtls.mkdir( KSPathUtils.parent( dummyPersonPath ))
end

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

function WFCatPersonBinaryDownloaderTest.rxTestGetPersonBinary( rxTest )
	local personId = "6f607906eefa4e9fb80da8fde2805c11"
	
	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/href/bogus/testing", "pseudo-master" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensurePersonDestinationFolderExistsfor( catalog, personId )

	local downloader = WFCatPersonBinaryDownloader( catalog )

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing' }
				}
			},
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForPerson( personId )

	rxTest:expectSingleValue(

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

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

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

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

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

function WFCatPersonBinaryDownloaderTest.rxTestGetPersonBinaryHttpError( rxTest )
	
	local personId = '6f607906eefa4e9fb80da8fde2805c11'
	
	local errorMessage = "Not found"
	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			{
				url = "/href/bogus/testing",
				fail = {
					errorMessage,
					headers = {
						status_code = '404',
					},
				},
				options = {
					requestCost = cost,
					requestPriority = priority
				}
			},
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensurePersonDestinationFolderExistsfor( catalog, personId )

	local downloader = WFCatPersonBinaryDownloader( catalog )

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing' }
				}
			},
		},

		':ignore:' )
	
	rxTest:expectSingleValue(

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

		{ personId, false, errorMessage, false } )

end

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

function WFCatPersonBinaryDownloaderTest.rxTestGetPersonBinaryDownloadAgainDifferentHref( rxTest )
		
	local personId = "6f607906eefa4e9fb80da8fde2805c12"
		
	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/href/bogus/testing", "pseudo-master" ),
			makeUrlResponse( "/href/bogus/testing2", "pseudo-master2" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensurePersonDestinationFolderExistsfor( catalog, personId )

	local downloader = WFCatPersonBinaryDownloader( catalog )

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing' }
				}
			},
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForPerson( personId )

	rxTest:expectSingleValue(

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

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

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

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

		catalog:docStore():applyOverlay {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing2' }
				}
			},
		},

		':ignore:' )

	downloader:requestPersonBinary( personId, personId )
	
	local observe = rxTest:observe( downloader:getResponseStream() )
	
	observe:expectData( personId, true, path, false )
	observe:expectData( personId, true, path, true )
	
	data = KSData.memoryMappedContentsOfFile( path )
	rxTest:expectSingleValue(

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

		"pseudo-master2" )

	data:close()
	
	observe:dispose()
end

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

function WFCatPersonBinaryDownloaderTest.rxTestGetPersonBinaryDownloadAgainSameHref( rxTest )
	
	local personId = "6f607906eefa4e9fb80da8fde2805c11"
		
	local catalogSpec = WFCatSpecMock( '98db98bfd554470dab2f862a4b853c40', kUserId, rxTest,

		{
			makeUrlResponse( "/href/bogus/testing", "pseudo-master" ),
		} )

	local catalog = WFCatMockCatalog.createWFCatalogForTestWithSpec( rxTest, catalogSpec )
	ensurePersonDestinationFolderExistsfor( catalog, personId )

	local downloader = WFCatPersonBinaryDownloader( catalog )

	rxTest:expectSingleValue(

		catalog:docStore():setDocValue {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing' }
				}
			},
		},

		':ignore:' )
		
	local path = catalog:fileSpec():pathForPerson( personId )

	rxTest:expectSingleValue(

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

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

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

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

		catalog:docStore():applyOverlay {
			_id = personId,
			_serverProvidedMetadata = {
				links = {
					[ '/rels/rendition_type/thumbnail2x' ] = { href = '/href/bogus/testing' }
				}
			},
		},

		':ignore:' )
		
	rxTest:expectSingleValue(

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

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

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

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

--------------------------------------------------------------------------------
local WFPlatformInfo = require 'WFPlatformInfo'

if WFPlatformInfo.isAndroid then
	return {}
else
	return WFRxTestCase.wrapSuite( 'WFCatPersonBinaryDownloaderTest', WFCatPersonBinaryDownloaderTest )
end

