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

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.

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

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

	-- WF.core.self_test
local WFRxTestCase = require "WFRxTestCase"

	-- WF.core.utils
local KSIdGenerator = require 'KSIdGenerator'
local KSTableUtils = require 'KSTableUtils'
local WFTableMerge = require 'WFTableMerge'

	-- Lrmobile_models
local LrmCatalogTestHelper = require 'LrmCatalogTestHelper'
local LrmAlbumModel = require 'LrmAlbumModel'
local LrmDocValueTestFactory = require 'LrmDocValueTestFactory'

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

if not WFPlatformInfo.isMobile() then
	return {}
end

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

local derefOpt = KSTableUtils.derefOpt

local LrmAlbumModelTest = {}

local TEST_TIMEOUT = 10

local wfCatalog, userId

local kAlbumId = KSIdGenerator.uuidInLowercaseHex()

local kExpectedAssetListOutput

if WFPlatformInfo.isAndroid then

	-- Android uses fewer attributes.
	-- Sending more attributes cause jni conversion
	-- to be slower.
	kExpectedAssetListOutput= {
		captureDate = "2012-01-02T20:54:00.485",
		croppedHeight = 150,
		croppedWidth = 150,
		fileName = "Image01.jpg",
		hasThumbnail = 1,
		importDate = "2012-01-02T20:54:00.485",
		importedByUser = "",
		isPopulated = true,
		isVideo = false,
		modifiedDate = "2018-04-03T20:54:00.485",
		thumbnailMD5 = "hash",
	}

else

	kExpectedAssetListOutput = {
		apertureValue = "100.0",
		cameraMaker = "Make",
		cameraModel = "Model",
		captureDate = "2012-01-02T20:54:00.485",
		commentCount = 0,
		croppedHeight = 150,
		croppedWidth = 150,
		exposureTime = "100",
		favoriteCount = 0,
		fileName = "Image01.jpg",
		flag = "unflagged",
		fnumber = "100.0",
		hasThumbnail = 1,
		height = 1000,
		isMergedHDR = 0,
		importedByUser = "",
		isVideo = 0,
		isoSpeedRatings = "100",
		modifiedDate = "2018-04-03T20:54:00.485",
		rating = 0,
		width = 1200,
	}

end

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

function LrmAlbumModelTest.setUp()

	local _

	wfCatalog, _, userId = LrmCatalogTestHelper.makeWFCatalog()

end

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

function LrmAlbumModelTest.tearDown()

	if wfCatalog then

		wfCatalog:close()
		wfCatalog = nil

	end

end

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

local function getSubmodel( model, submodelName )

	return model.models[submodelName]

end

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

local function makeSubmodel( model, submodelName, ... )

	return getSubmodel( model, submodelName )( model, ... )

end

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

-- @mark assetList model

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

function LrmAlbumModelTest.rxTestCannotInitModelWithoutWFCatalog( rxTest )
	-- fails with a nil value
	rxTest:expectSpecificError('bad argument #1 (wfCatalog) to albumModel (WFCatalog expected, got nil)', function ()
		LrmAlbumModel.albumModel( nil, kAlbumId )
	end)

	-- succeeds with a wfCatalog instance
	LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

end

function LrmAlbumModelTest.rxTestAssetList( rxTest )

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			_id = kAlbumId,
			type = 'album',
			docId = kAlbumId,
			overlay = {
				subtype = 'collection',
				private = false,
				download = false,
				updated = '2012-08-15T15:22:29',
				created = '2012-08-15T15:22:29',
			},
		},
		':ignore:' )

	rxTest:expectSingleValue( LrmDocValueTestFactory.insertAlbumAssets( wfCatalog:docStore(), kAlbumId, 1 ), ':ignore:' )

	local albumModel = LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

	local albumObs = rxTest:observe( albumModel.value )
	rxTest:finally( function()
		albumObs:dispose()
	end )

	albumObs:expectData( nil )

	local args = {
			'captureDate', 	-- sortCriteria
			true, 			-- ascending
			{}, 			-- assetFilter
			{},				-- assetTypeFilter
			{},				-- keyword
			{},				-- edited
			0, 				-- ratingFilter
			'>=', 			-- ratingComparisonOperator,
		}

	local assetList = makeSubmodel( albumModel, 'assetListModel',  unpack( args ) ).value
		:pluck( 'albumInfo', 'photos' )
		:map( function( photos )
			if photos then
				for _, photo in ipairs( photos ) do
					photo.id = nil
				end
			end

			return photos
		end )


	local assetListObs = rxTest:observe( assetList )
	rxTest:finally( function()
		assetListObs:dispose()
	end )

	assetListObs:expectData( {
		kExpectedAssetListOutput
	} )

end

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

-- @mark cover asset model

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

function LrmAlbumModelTest.rxTestAlternativeCoverAssetId( rxTest )

	rxTest:setTimeLimit( TEST_TIMEOUT )

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay{
			type = 'album',
			_id = kAlbumId,
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )


	rxTest:expectSingleValue( LrmDocValueTestFactory.insertAlbumAssets( wfCatalog:docStore(), kAlbumId, 1 ), ':ignore:' )

	local assetId

	rxTest:expectSingleValue( wfCatalog:indexStore():queryOnce{ sql = 'SELECT docId FROM coreInfo' }
								:map( function( rows )

									assetId = derefOpt( rows, 1, 1 )
									return assetId

								end ), ':ignore:' )

	local albumModel = LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

	local albumObs = rxTest:observe( albumModel.value )
	rxTest:finally( function()
		albumObs:dispose()
	end )

	albumObs:expectData( nil )

	local alternativeCoverAssetId = makeSubmodel( albumModel, 'alternativeCoverAssetId' ).value
		:take( 1 )

	rxTest:expectSingleValue( alternativeCoverAssetId, assetId )

end


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

-- @mark cacheSize model

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

function LrmAlbumModelTest.rxTestCacheSize( rxTest )

	rxTest:setTimeLimit( TEST_TIMEOUT )

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album',
			_id = kAlbumId,
			name = 'test album',
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )


	local albumModel = LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

	local albumObs = rxTest:observe( albumModel.value )
	rxTest:finally( function()
		albumObs:dispose()
	end )

	albumObs:expectData( nil )

	local cacheSizeObs = rxTest:observe( makeSubmodel( albumModel, 'cacheSizeModel' ).value )
	rxTest:finally( function()
		cacheSizeObs:dispose()
	end )

	cacheSizeObs:expectData( 0 )

	local assets = { LrmDocValueTestFactory.makeCompleteAsset(), LrmDocValueTestFactory.makeCompleteAsset() }

	-- make the second asset a deleted image
	KSTableUtils.setNested( assets, 'deleted_image', 2, 'subtype' )

	rxTest:expectSingleValue( wfCatalog:docStore():bulkApplyOverlay( assets ), ':ignore:' )

	local albumAssets = {
		LrmDocValueTestFactory.makeAlbumAsset( kAlbumId, assets[ 1 ]._id ),
		LrmDocValueTestFactory.makeAlbumAsset( kAlbumId, assets[ 2 ]._id )
	}

	rxTest:expectSingleValue( wfCatalog:docStore():bulkApplyOverlay( albumAssets ), ':ignore:' )

	cacheSizeObs:expectData( 1141718 )

	rxTest:expectSingleValue( wfCatalog:docStore():deleteDoc( albumAssets[ 1 ]._id ), ':ignore:' )

	cacheSizeObs:expectData( 0 )

end

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

-- @mark flag status

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

function LrmAlbumModelTest.rxTestFlagStatus( rxTest )

	rxTest:setTimeLimit( TEST_TIMEOUT )

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album',
			_id = kAlbumId,
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )

	local albumModel = LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

	local albumObs = rxTest:observe( albumModel.value )
	rxTest:finally( function()
		albumObs:dispose()
	end )

	albumObs:expectData( nil )

	local docValue = LrmDocValueTestFactory.makeCompleteAsset()

	WFTableMerge.applyOverlay( docValue, {
			reviews = {
				[ userId ] = {
					flag = 'pick',
				}
			}
		} )

	local assetId = docValue._id

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay( docValue ), ':ignore:' )

	local flagStatusCountModel = makeSubmodel( albumModel, 'flagStatusCountModel' )

	local flagObs = rxTest:observe( flagStatusCountModel.value )

	flagObs:expectData {
			pick = 0,
			reject = 0,
			unflagged = 0,
		}

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album_asset',
			_id = KSIdGenerator.uuidInLowercaseHex(),
			album = {
				id = kAlbumId,
			},
			asset = {
				id = assetId,
			}
		},
		':ignore:' )

	flagObs:expectData {
			pick = 1,
			reject = 0,
			unflagged = 0,
		}

	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			_id = assetId,
			reviews = {
				[ userId ] = {
					flag = 'reject',
				}
			}
		},
		':ignore:' )

	flagObs:expectData {
			pick = 0,
			reject = 1,
			unflagged = 0,
		}

end

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

-- @mark best photos

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

function LrmAlbumModelTest.rxTestBestPhotos( rxTest )

	local function pluckAssetIdTopicIdSortOrder( photoList )

		local photos = KSTableUtils.derefOpt( photoList, 'albumInfo', 'photos' )
		if not photos then
			return nil
		end

		local result = {}

		for _, photo in ipairs( photos ) do

			result[ #result + 1 ] = {
				photo.id,
				photo.topicId,
				photo.sortOrder
			}
		end

		return result

	end

	rxTest:setTimeLimit( TEST_TIMEOUT )

	-- create the normal album
	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album',
			subtype = 'collection',
			_id = kAlbumId,
			name = 'test album',
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )

	local clusterId = KSIdGenerator.uuidInLowercaseHex()

	-- create the cluster
	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album',
			subtype = 'cluster',
			_id = clusterId,
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )

	local albumModel = LrmAlbumModel.albumModel( wfCatalog, kAlbumId )

	local bestPhotosListModel = makeSubmodel( albumModel, 'bestPhotosListModel', clusterId )

	local bestPhotosObs = rxTest:observe( bestPhotosListModel.value:map( pluckAssetIdTopicIdSortOrder ) )

	bestPhotosObs:expectData( {} )

	local assetIds

	rxTest:expectSingleValue( LrmDocValueTestFactory.insertAlbumAssets( wfCatalog:docStore(), kAlbumId, 2 )
		:map( function( ids )
			assetIds = ids
			return assetIds
		end ),
		':ignore:' )


	local topicId = KSIdGenerator.uuidInLowercaseHex()

	-- create the topic
	rxTest:expectSingleValue( wfCatalog:docStore():applyOverlay {
			type = 'album',
			subtype = 'topic',
			_id = topicId,

			parent = {
				id = clusterId
			},

			cover = {
				id = assetIds[1]
			},
			updated = '2012-08-15T15:22:29',
			created = '2012-08-15T15:22:29',
		},
		':ignore:' )

	-- create the topic album_assets

	local topicAlbumAssets = {
		LrmDocValueTestFactory.makeAlbumAsset( topicId, assetIds[1] ),
		LrmDocValueTestFactory.makeAlbumAsset( topicId, assetIds[2] )
	}

	topicAlbumAssets[1].order = '2305843009232293951'
	topicAlbumAssets[2].order = '2305843009232293950'

	rxTest:expectSingleValue( wfCatalog:docStore():bulkApplyOverlay ( topicAlbumAssets ),
		':ignore:' )


	local expected = {
		{
			KSTableUtils.derefOpt( topicAlbumAssets, 1 , 'asset', 'id' ),
			KSTableUtils.derefOpt( topicAlbumAssets, 1 , 'album', 'id' ),
			KSTableUtils.derefOpt( topicAlbumAssets, 1 , 'order')
		},
		{
			KSTableUtils.derefOpt( topicAlbumAssets, 2, 'asset', 'id' ),
			KSTableUtils.derefOpt( topicAlbumAssets, 2, 'album', 'id' ),
			KSTableUtils.derefOpt( topicAlbumAssets, 2, 'order')
		},
	}

	-- INFO [immisch 2020-07-16]: This is the query used on iOS
	rxTest:expectSingleValue( wfCatalog:indexStore():queryOnce{
			sql = [[ SELECT assetId, albumId, sortOrder FROM album_asset
						INNER JOIN albums
							ON (albums.docId == album_asset.albumId and albums.subtype == 'topic' and albums.parentId == ? )
						ORDER BY sortOrder DESC ]],
			quiesceUntilUpToDate = true,
			clusterId
		},
		expected )

	bestPhotosObs:expectData( expected )

end

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

return WFRxTestCase.wrapSuite( LrmAlbumModelTest )
