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

ADOBE CONFIDENTIAL
------------------
Copyright 2015 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 WFPlatformInfo = require 'WFPlatformInfo'

	-- WF.core.rxLua
local WFRxPromiseBridge = require 'WFRxPromiseBridge'

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

	-- WF.oz_client
local WFOzPurgeSettings = require 'WFOzPurgeSettings'

	-- WF.lrmobile_models
local LrmCatAlbumAsset = require 'LrmCatAlbumAsset'
local KSPromises = require 'KSPromises'

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

local addAssetArrayToCatalogP

if WFPlatformInfo.isiOS then
	local LriImport = require 'LriImport'
	addAssetArrayToCatalogP = LriImport.addAssetArrayToCatalogP
else
	local LrmImport = require 'LrmImport'
	addAssetArrayToCatalogP = LrmImport.addAssetArrayToCatalogP
end

local asKSPromise = WFRxPromiseBridge
local logger = WFLogger 'LrmLibraryImportViaReferencesModelImp'
	--:setLevel 'DEBUG'

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

local LrmLibraryImportViaReferencesModelImp = {}

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

function LrmLibraryImportViaReferencesModelImp:addAssetArrayToCatalog( assetArray, optAlbumId, options )

	assert( assetArray )
	
	options = options or {}
	
	options.minimumFreeDiskSpace = WFOzPurgeSettings.minimumFreeSpace()
	
	local catalog = self.catalog
	
	local importP = addAssetArrayToCatalogP( catalog, assetArray, options )
		
		:mapDataP_new( function( addedAssets )
			
			if optAlbumId and optAlbumId ~= '' then
			
				local assetIds = {}
				
				for _, asset in ipairs( addedAssets ) do
				
					table.insert( assetIds, asset.assetId )
					
				end
				
				return LrmCatAlbumAsset.addAssetsToAlbumWithOrder( catalog, optAlbumId, assetIds, options )
				
					:call( asKSPromise )
				
					:mapDataP_new( function()
					
						return addedAssets
						
					end )
					
			end
			
			return addedAssets
			
		end )
		
	return {
		value = importP:untilResolvedB( 'data', WFUnknown.value() )
	}
	
end

-- This is specific to android
function LrmLibraryImportViaReferencesModelImp:addAssetToV2Catalog( assetInfo, binaryData, optAlbumId, optRedactionOptions )

    assert( assetInfo )
	
	logger:debugf("addAssetToV2Catalog: optAlbumId:%s optRedactionOptions:%s ", optAlbumId, optRedactionOptions )

    local assetArray = {}

    if assetInfo.develop and assetInfo.develop.profiles then

        local isEmpty = true

        for _,_ in pairs(assetInfo.develop.profiles) do
            isEmpty = false
        end

        if isEmpty then
            assetInfo.develop.profiles = nil
        end

    end

    local originalData = binaryData.originalData
    local proxyData = binaryData.proxyData
    if      assetInfo
            and assetInfo.docValue
            and assetInfo.docValue.importSource
            and not assetInfo.docValue.importSource.importTimeStamp
    then
        local KSDate = require 'KSDate'
        assetInfo.importSource[ 'importTimestamp' ] = KSDate.timeInIso8601Format( nil, false )
    end

    local thumbNailRendition = {}
    thumbNailRendition.renditionName = 'thumbnail2x'
    thumbNailRendition.renditionData = binaryData["thumbnail"]

    local previewRendition = {}
    previewRendition.renditionName = 'preview'
    previewRendition.renditionData = binaryData["preview"]

    local renditions = { thumbNailRendition, previewRendition }

    -- original = assetInfo._localOnly.localUrl,
    local importAsset = {
        docValue = assetInfo,
        renditions = renditions,
    }

    local KSData = require 'KSData'
    if originalData and KSData.isData( originalData ) then
        importAsset["original"] = originalData
    else
		importAsset["original"] = binaryData.originalPath
		importAsset["originalfd"] = binaryData.originalFD
	end

	importAsset["fileSize"] = binaryData.fileSize


    if proxyData and KSData.isData( proxyData ) then
        importAsset["proxy"] = proxyData
    end

    assetArray[ #assetArray + 1 ] = importAsset

    local function updateCustomProfileInfoIfAvailbleP(catalog)

        if assetInfo._localOnly.customAppliedCameraProfileDigest and assetInfo and assetInfo.xmp and assetInfo.xmp.tiff and assetInfo.xmp.tiff.Model then

            local LrmWFOzProfileUtils = require 'LrmWFOzProfileUtils'
            return LrmWFOzProfileUtils.getCustomCameraProfilesP(catalog, assetInfo._localOnly.customAppliedCameraProfileDigest,
                assetInfo.xmp.tiff.Model)
            :mapP(function(_, profileFilename, profileLink)

                if profileFilename and profileLink then
                    assetInfo.develop.profiles.camera = {
                        filename = profileFilename,
                        href = profileLink
                    }
                end

                assetInfo._localOnly.customAppliedCameraProfileDigest = nil

            end)
        end

        return KSPromises.resolvedPromiseP( 'data', true )

    end

    local function addAssetArrayToCatalog(assetArray, albumId)

        assert( assetArray )

        local importOptions = {
            minimumFreeDiskSpace = WFOzPurgeSettings.minimumFreeSpace(),
        }

        local catalog = self.catalog

        local importP = updateCustomProfileInfoIfAvailbleP(catalog)
        :mapDataP(function()

            return addAssetArrayToCatalogP( catalog, assetArray, importOptions )

        end)

        :mapDataP_new( function( addedAssets )

            if albumId and albumId ~= '' and albumId ~= '10002000300040005000600070008000' then

                local assetIds = {}

                for _, asset in ipairs( addedAssets ) do

                    table.insert( assetIds, asset.assetId )

                end

                return LrmCatAlbumAsset.addAssetsToAlbumWithOrder( catalog, albumId, assetIds, optRedactionOptions )

				:call( asKSPromise )

                :mapDataP_new( function()

                    return {
                        state = true,
                        addedAssets = addedAssets
                    }

                end )

            end

            return {
                state = true,
                addedAssets = addedAssets
            }

        end )

        :mapP( function( status, error )

            if status == 'error' then
                return KSPromises.resolvedPromiseP( 'data', {
                    state = false,
                    error = error
                } )
            end

        end)

        return {
            value = importP:untilResolvedB( 'data', WFUnknown.value() )
        }
    end

    return addAssetArrayToCatalog( assetArray, optAlbumId)
end
--------------------------------------------------------------------------------

return LrmLibraryImportViaReferencesModelImp
