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

ADOBE CONFIDENTIAL
------------------
Copyright 2014 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 LrmAssetQueries = require 'LrmAssetQueries'

	-- WF.core.os
local KSPathUtils = require 'KSPathUtils'
local WFFileUtils = require 'WFFileUtils'
local WFPlatformInfo = require 'WFPlatformInfo'

	-- WF.core.utils
local KSIdGenerator = require 'KSIdGenerator'
local WFCapabilities = require 'WFCapabilities'

	-- WF.core.utils.logging
local WFLogger = require 'WFLogger'

	-- WF.core.lua
local KSData = require 'KSData'

	-- WF.oz_client.catalog
local OzCatalogUrls = require 'OzCatalogUrls'
local OzCatHelperFns = require 'OzCatHelperFns'

	-- WF.oz_client.ims
local WFImsAppIdentity = require "WFImsAppIdentity"

	-- WF.web.http_client
local WFRxHttpClient = require 'WFRxHttpClient'

	-- WF.web.utils
local WFURI = require 'WFURI'

local logger = WFLogger "LriWFOzProfileUtils"
--	:setLevel 'debug'

local asKSPromise = require 'WFRxPromiseBridge'

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

local LriWFOzProfileUtils = {}

local kLensPresetDirectory = nil
local kCameraPresetDirectory = nil

local cAdobeStandardDcp = "Adobe Standard.dcp"
local cAdobeStandard = "Adobe Standard"

local cCameraSearch = " Camera "
local cCamera = "Camera"
		
--------------------------------------------------------------------------------

local function getLensPresetDirectory()

	if not kLensPresetDirectory then
		kLensPresetDirectory = assert( WFCapabilities.getCapability( 'WFOzAppConfig.lensPresetDirectory' ) )
	end
	
	return kLensPresetDirectory
	
end

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

local function getCameraPresetDirectory()

	if not kCameraPresetDirectory then
		kCameraPresetDirectory = assert( WFCapabilities.getCapability( 'WFOzAppConfig.cameraPresetDirectory' ) )
	end
	
	return kCameraPresetDirectory
	
end

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

local function getLocalProfileDirectory( profileType, filename )

	local cVersion = "1.0"
	local directoryPath
	
	if profileType == 'camera' then
	
		directoryPath = getCameraPresetDirectory()

		if string.find( filename, cAdobeStandardDcp .. "$" ) then
			directoryPath = KSPathUtils.child( directoryPath, cAdobeStandard )
		else
			directoryPath = KSPathUtils.child( directoryPath, cCamera )
			
			local sentinalPos = filename:find( cCameraSearch )

			if sentinalPos > 0 then
				directoryPath = KSPathUtils.child( directoryPath, filename:sub( 1, sentinalPos ) )
			end
		end
		
	elseif profileType == 'lens' then
	
		directoryPath = getLensPresetDirectory()
		
		directoryPath = KSPathUtils.child( directoryPath, cVersion )
		directoryPath = KSPathUtils.child( directoryPath, "MakerName" )
		
	else
		-- error out
	end
	
	return directoryPath
	
end
 
--------------------------------------------------------------------------------

local function noncachedProfilesForAssetP( catalog, assetId )

	local sql = LrmAssetQueries.unsyncedProfiles
	if WFPlatformInfo.isiOS then
		sql = LrmAssetQueries.unsyncedCameraProfiles
	end
	
	return catalog:indexStore():queryP( sql, assetId )
	:mapDataP( function( status, data )
	
		local profiles = {}
		
		for i=1, #data do
			local profile = {
				type = data[ i ][ 2 ],
				filename = data[ i ][ 3 ],
				masterUrl = data[ i ][ 4 ],
				uniqueId = data[ i ][ 5 ],
			}
			table.insert( profiles, profile )
		end
		
		return KSPromises.resolvedPromiseP( 'data', profiles )
	end )
end

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

local function ensureProfileExistP( catalog, profiles, index )

	if index <= #profiles then
	
		local profile = profiles[index]
		local profileType = profile.type
		local filename = profile.filename
		
		local imageBaseUrl = WFCapabilities.getCapability( "OzCatalogUrls.downloadImagesBaseUrl" )
	
		if not imageBaseUrl then
			imageBaseUrl = OzCatalogUrls.baseServerUrl
		end
		
		return catalog
		:ozUserP()
		:mapDataP_new( function( user )

			if user:userId() == "00000000000000000000000000000000" then
				local freemiumUrl = imageBaseUrl .. "/v2/profiles?subtype=" ..
										profileType .. "_profile&file_name=" .. WFURI.escape( filename )

				local imsClientId = WFImsAppIdentity.getClientIdAndSecret() -- we don't care about secret
				local options = {
					requestHeaders = {
						{ header = 'X-Api-Key', value = imsClientId }
					}
				}

				return WFRxHttpClient.get( freemiumUrl, options )
				:call( asKSPromise )
			else
				local ozUrl = OzCatHelperFns.checkForRelativeUrlAndAppendBase( profile.masterUrl, imageBaseUrl )
		
				return user:get( ozUrl )
				:call( asKSPromise )
			end

		end )
		
		:mapDataP( function( status, data )
		
			local directoryPath = getLocalProfileDirectory( profileType, filename )
			
			local filePath = KSPathUtils.child( directoryPath, filename )
		
			WFFileUtils.mkdir( directoryPath )
			
			logger:debugf( "save profile at %s for %s", filePath, profileType )
			
			KSData.saveToFile( data, filePath )
			
			return KSPromises.resolvedPromiseP( 'data', profile )
			
		end )
		:mapDataP( function( status, profile )
		
			if status == 'data' then
			
				local profileId = KSIdGenerator.uuidInLowercaseHex()
				
				local innerResultP = catalog:docStore():applyOverlayToDocumentP {
						docType = 'profile',
						docIds = profileId,
						overlay = {
							_localOnly = {
								subtype = profile.type,
								fileName = profile.filename,
								uniqueId = profile.uniqueId,
							}
						},
					}
				return innerResultP
				
			end
			
			return KSPromises.resolvedPromiseP( 'data', true )
						
		end )
		:mapP( function( _, data )
		
			return ensureProfileExistP( catalog, profiles, index + 1 )
			
		end )
	else
		return KSPromises.resolvedPromiseP( 'data', true )
	end
	
end

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

function LriWFOzProfileUtils.ensureProfilesExistLocallyP( catalog, assetId )

	local updateAcrProfileCache = false
	
	return noncachedProfilesForAssetP( catalog, assetId )
		:mapDataP( function( _, profiles )
		
			if #profiles >= 1 then
			
				updateAcrProfileCache = true
				return ensureProfileExistP( catalog, profiles, 1 )
				
			else
				return KSPromises.resolvedPromiseP( 'data', true )
			end
			
		end )
		:mapP( function( status, data )
		
			local result = {
				status = status,
				updateAcrProfileCache = updateAcrProfileCache
			}
			
			return KSPromises.resolvedPromiseP( 'data', result  )
			
		end )
	
end

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

return LriWFOzProfileUtils
