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

NmbProfileBinaryDownloader.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.

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

local Rx = require 'Rx'
local Observable = Rx.Observable
local WFCloseSupport = require 'WFCloseSupport'
local WFRxHttpClient = require 'WFRxHttpClient'
local WFAsyncFileUtils = require 'WFAsyncFileUtils'
local KSTableUtils = require 'KSTableUtils'
local KSPathUtils = require 'KSPathUtils'
local WFFileUtils = require 'WFFileUtils'
local KSData = require 'KSData'
local WFURI = require 'WFURI'
local WFLogger = require 'WFLogger'

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

local derefOpt = KSTableUtils.derefOpt

local logger = WFLogger 'NmbProfileBinaryDownloader'
	--:setLevel( 'DEBUG' )

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

local function downloadOneBinary( self, identifier, href, downloadPriority, downloadCost )

	logger:debugf( "downloadOneBinary identifier = %s href = %s" , identifier, href )

	local options = {
		requestPriority = downloadPriority or WFRxHttpClient.requestPriorityMedium,
		requestCost = downloadCost or WFRxHttpClient.requestCostDefault,
	}

	return self._catalog:ozCatalogSpec():getBinary( href, options )

		:flatMapLatest( function( result, headers )

			local headerContentLength = tonumber( derefOpt( headers, "Content-Length" ) ) or 0
			local headerContentEncoding = tostring( derefOpt( headers, "Content-Encoding" ) ) 
			local dataLength = KSData.length( result )
			
			if dataLength ~= headerContentLength and headerContentEncoding ~= 'gzip' then
				logger:errorf( "downloadOneBinary identifier = %s href = %s data length (%d) doesn't match headers.Content-Length (%d)",
							  identifier, href, dataLength, headerContentLength )
				return Observable.throw( "Error downloading file, dataLength doesn't match headers.Content-Length", headers )
			end

			return Observable.just( result, headers )

		end )

		:tap(
			function( result )

				logger:infof( "downloadOneBinary: Download successful for identifier = %s href = %s",
							  identifier, href )

			end,
			function( message, headers )

				logger:errorf( "downloadOneBinary: Failed for identifier = %s href = %s FAILED with message %s\n\nheaders %s\n\n",
							   identifier, href, message, headers )

			end )
		:catch( function( message, headers )
		
			return Observable.throw( message, headers, identifier, href )
		
		end ) 

end

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

local function saveToFile( self, profileInfo, blob )

	local path = self._catalog:fileSpec():pathForStandardProfile( profileInfo.relativePath )
	
	-- SPAM [ashj 2018-07-30]: Oz global profile catalog
	-- right now has multiple profiles for the same fileName.
	-- It is not yet clear, whether we should have multiple
	
	
	return WFAsyncFileUtils.saveToFile( blob, path )
		:catch( function( err )
			
			-- if the parent folder doesn't exists, then
			-- create the folder and try again.
			
			-- The relative path obtained from ACR is in
			-- the form of URI. Need to convert it to
			-- platform specific form before trying to
			-- create the directories.
			local path = WFURI.uriPathToFilePath( path )
			local parentFolder = KSPathUtils.parent( path )
			WFFileUtils.mkdir( parentFolder )
			return WFAsyncFileUtils.saveToFile( blob, path )
		end )
		:map( function()
			return path
		end )
end

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

local function getHrefForFileName( self, fileName )
	local query = self._profileCatalog:indexStore():queryOnce {
		sql = [[ SELECT href FROM profiles WHERE filename = ? ]],
		quiesceUntilUpToDate = true,
		singleColumnQuery = true,
		fileName
	}
	
	return query
		:map( function( hrefs )
			
			if hrefs and hrefs[ 1 ] then
				return hrefs[ 1 ]
			end
			
			logger:errorf( "No profile found for filename: %s", fileName )
			error( "No profile found" )
		end )
end

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

local function downloadProfileSubn( self, profileInfo, httpPriority )
	
	local fileName = profileInfo.fileName
	
	return getHrefForFileName( self, fileName )
		:flatMap( function( href )
			
			return downloadOneBinary( self, fileName, href, httpPriority )
		end )
		
		:flatMap( function( blob )
			
			return saveToFile( self, profileInfo, blob )
				:finally( function()
					if blob then
						blob:close()
					end
				end )
			
		end )
		
		:subscribe(
			function( path )
				self._inFlightRequests[ fileName ] = nil
				self._binaryDownloadResponseStream:onNext( fileName, true, path )
			end,
			
			function( err, ... )
				self._inFlightRequests[ fileName ] = nil
				self._binaryDownloadResponseStream:onNext( fileName, false, err, ... )
			end
		)
end

--------------------------------------------------------------------------------
-- SPAM [ashj 2018-07-30]: Unlike other assets, the file path
-- information doesn't get stored in the document for standard
-- profile, since we are downloading separate copies for each user.

local NmbProfileBinaryDownloader = {
	
	_catalog = false,
	
	_profileCatalog = false,
	
	_binaryDownloadResponseStream = false,
	
	_inFlightRequests = false,
	
	WFCloseSupport.addCloseSupportMethods,
}

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

function NmbProfileBinaryDownloader:__init( catalog, profileCatalog )

	self._catalog = catalog
	self._profileCatalog = profileCatalog
	self._inFlightRequests = {}
	self._binaryDownloadResponseStream = Rx.Subject()
end

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

function NmbProfileBinaryDownloader:requestProfileBinary( profileInfo, httpPriority )
	
	local fileName = profileInfo.fileName
	logger:debugf( "requestProfileBinary fileName: %s", fileName )
	
	local maybeInFlightRequest = self._inFlightRequests[ fileName ]
	if maybeInFlightRequest then
		-- New request received for the assetid, which is
		-- already in progress. If its with a higher priority,
		-- then remove the old request and add new one.
		logger:warnf( "Multiple requests for the same style docId: %s, priority:%s", 
			profileInfo.fileName, httpPriority )
		
		if httpPriority and httpPriority > maybeInFlightRequest.request.httpPriority then
			if maybeInFlightRequest.subscription then
				maybeInFlightRequest.subscription:dispose()
			end
			self._inFlightRequests[ fileName ] = nil
		else
			-- Priority of the new request is less than or
			-- equal to the old one. Maybe the idle download
			-- got triggered when the high priority one is
			-- going on. Let the old request continue.
			return
		end
		
	end
	
	httpPriority = httpPriority or WFRxHttpClient.requestPriorityMedium

	local subscription = downloadProfileSubn( self, profileInfo, httpPriority )

	self._inFlightRequests[ fileName ] = {
		request = {
			profileInfo = profileInfo,
			httpPriority = httpPriority,
		},
		subscription = subscription
	}
end

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

function NmbProfileBinaryDownloader:cancelBinaryRequest( fileName )
	
	local maybeInFlightRequest = self._inFlightRequests[ fileName ]
	if maybeInFlightRequest then
		maybeInFlightRequest.subscription:dispose()
		self._inFlightRequests[ fileName ] = nil
	end
end

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

function NmbProfileBinaryDownloader:getResponseStream()
	
	return self._binaryDownloadResponseStream
end

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

function NmbProfileBinaryDownloader:close()
	if self._binaryDownloadResponseStream then
		self._binaryDownloadResponseStream:dispose()
		self._binaryDownloadResponseStream = nil
	end
end

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

return Rx.Class 'NmbProfileBinaryDownloader'( NmbProfileBinaryDownloader )