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

OzCatHelperFns.lua

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

ADOBE CONFIDENTIAL
------------------
Copyright 2012 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 KSPromises = require "KSPromises"
local KSReactive = require "KSReactive"
local KSJsonDecoder = require "KSJsonDecoder"
local WFWorkerThread = require "WFWorkerThread"
local WFCloseSupport = require 'WFCloseSupport'
local OzCatalogUploadStatus = require "OzCatalogUploadStatus"
local KSPathUtils = require "KSPathUtils"

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

local DISABLE_MOST_FETCHES = false

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

local hasDownloadedSuccessfully_impB = WFCloseSupport.memoizeFn( function( catalogId )

	local BabluEP = WFWorkerThread( "BabluImp.lua" )

	local hasDownloadedB =  BabluEP:requestB {
		message = 'hasDownloadedSuccessfullyB',
		arguments = catalogId,
		startingValue = false
	}

	BabluEP:close()
	
	return hasDownloadedB
end )

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

local function hasDownloadedSuccessfullyB( ... )
	
	return hasDownloadedSuccessfully_impB( ... )
		:autoCloseRelayB()

end

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

local progressIncompleteB = KSReactive.constantB( 0, 1 )
local nilP = KSPromises.resolvedPromiseP( 'data', nil )

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

-- This function locates the originalFilePath in the given document and returns
-- the corrected version.

local function findAndCorrectOriginalPath( docValue )

	local localPath = docValue
					and docValue._localOnly
					and docValue._localOnly.originalFilePath
						
	-- Temporary check to correct the local file path and replace
	-- 'Adobe Carousel Library.cr' with 'Adobe Revel Library.cr'
		
	-- FIXME [ngautam 2011-11-15] This should really be done via an upgrade process
	-- that updates the database with the correct file paths but this is not
	-- feasible in the current time frame.
		
	localPath = OzCatalogUploadStatus.checkAndCorrectLocalPath( localPath )
	return localPath
	
end

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

local function importSourceFileName( photoInfo )

	local name = photoInfo
			 and photoInfo.importSource
			 and photoInfo.importSource.fileName
			
	-- We've had some clients write full paths into this field. Sigh.
	-- KSPathUtils.leafName also works on forward slash on Windows platforms
			
	if name then
		name = KSPathUtils.leafName( name )
	end
	
	return name

end

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

local function importFileNameFromPhotoInfo( photoInfo, optSuffix )

	local name = importSourceFileName( photoInfo )

	if not name then
		name = photoInfo.captureDate:sub( 12 ):gsub( '[:Z]', '' )
		
		if optSuffix then
			name = name .. optSuffix
		end
	elseif optSuffix then
		name = name:gsub( '\.[^.]*$' , optSuffix)
	end
	
	return name

end

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

local function processHttpRequestResult( self, status, data, headers )

	if status == 'error' then
	
		if headers and headers.status_code == '403' then
		
			-- Set the access error behavior

			local result, eData = pcall( KSJsonDecoder.decodeWebSafeJson, data )
			
			if result and eData then
			
				local error_code = tonumber( eData.code )
				self._accessErrorB:set( error_code )
				
			end
			
		end
		
	else
	
		self._accessErrorB:set( false )
		
	end
	
end

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

local function checkForRelativeUrlAndAppendBase( possibleRelativeUrl, base )

	local completeUrl
	
	if possibleRelativeUrl:match( "^/" ) then
		completeUrl = string.format( "%s%s", base, possibleRelativeUrl )
	else
		completeUrl = possibleRelativeUrl
	end
	
	return completeUrl
	
end

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

return {
	DISABLE_MOST_FETCHES = DISABLE_MOST_FETCHES,

	hasDownloadedSuccessfullyB = hasDownloadedSuccessfullyB,
	progressIncompleteB = progressIncompleteB,

	nilP = nilP,
	
	findAndCorrectOriginalPath = findAndCorrectOriginalPath,
	importSourceFileName = importSourceFileName,
	importFileNameFromPhotoInfo = importFileNameFromPhotoInfo,
	processHttpRequestResult = processHttpRequestResult,
	checkForRelativeUrlAndAppendBase = checkForRelativeUrlAndAppendBase,
	
}
