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

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.

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

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

	-- WF.core.string
local KSStringUtils = require 'KSStringUtils'

	-- WF.core.reactive
local KSPromises = require 'KSPromises'

	-- WF.web.json
local KSJsonDecoder = require 'KSJsonDecoder'

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

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

local LrmOzCatalogUtils = {}

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

local function hasLrCatalogP( catalogInfo )

	for i, catalog in ipairs( catalogInfo.catalogs ) do
			
		local subtype = KSStringUtils.lower( catalog.subtype )
		if subtype == 'x-lightroom' or subtype == 'lightroom' then
			return KSPromises.resolvedPromiseP( 'data', catalog.id )
		end
	end
	
	return KSPromises.resolvedPromiseP( 'data', nil )
	
end

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

local function listLrCatalogsP( user )

	local catalogInfoUrl = string.format( '%s/v1.0/catalogs?subtype=%s',
			OzCatalogUrls.baseServerUrl,
			WFURI.escape( WFCapabilities.getCapability( "WFOzCatalog.subtype" ), 'http_query_key' ) )

	return user:getP( catalogInfoUrl )
	
	:mapDataP( KSJsonDecoder.decodeWebSafeJson_stripNullP )
end

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

function LrmOzCatalogUtils.ensureLrCatalogExistsP( user )

	local ensureLrP = listLrCatalogsP( user )
	:mapDataP( function( _, catalogs )
		
		return hasLrCatalogP( catalogs )
		
	end )
	:mapDataP( function( _, catalogId )
	
		if catalogId == nil then
			
			debug.print( "Default catalog created" )
			return user:createCatalogP( { name = 'lightroom', subtype = 'lightroom' } )
			
		else
			return KSPromises.resolvedPromiseP( 'data', true )
		end
		
	end )
	
	ensureLrP:runUntilDone()
	
	return ensureLrP
	
end


return LrmOzCatalogUtils
