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

ADOBE CONFIDENTIAL
------------------
Copyright 2013 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 KSTableUtils = require 'KSTableUtils'

	--WF.config
local LrmConfig = require 'LrmConfig'

	-- WF.oz_client.lrmobile
local LrmCatSyncStatus = require 'LrmCatSyncStatus'

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

local derefOpt = KSTableUtils.derefOpt

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

local LriSyncStatusModel = {}
local Model = {}

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

local function getUploadProgress( catalog )

	local numNeedingUploadQuery = catalog:indexStore():query {

		sql = [[SELECT count( DISTINCT sourceAssetId ) 
					FROM needsBinaryUpload
					WHERE docType == 'asset' ]],
		calm = 2,
		quiesceUntilUpToDate = true,
		singleColumnQuery = true
	}

	:map( function( progressRows )

		local binaryUploadCount = derefOpt( progressRows, 1 ) or 0

		return binaryUploadCount

	end )

	:distinctUntilChanged()

	return numNeedingUploadQuery

end

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

local function getDetailedUploadProgress( catalog )

	local uploadProgressStaus = catalog:getSyncClient():getDetailedUploadProgress()
	:map( function ( progressReport ) 
		return {
			totalFileSize = progressReport.totalBytesNeedToUpload,
			bytesUploaded = progressReport.totalBytesUploadedSoFar
		}
	end )

	return uploadProgressStaus

end

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

-- @mark Sub models

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

function Model:makeBinaryDownloadProgressAndAlbumModel( binaryDownloadStrategy )

	binaryDownloadStrategy = binaryDownloadStrategy or LrmConfig.StrategyPreferProxy

	-- From https://sqlite.org/nulls.html:
	-- I have about decided that SQL's treatment of NULLs is capricious and cannot be
	-- deduced by logic.  It must be discovered by experiment.

	local masterRenditionNames, proxyRenditionNames = LrmCatSyncStatus.getDownloadRenditionNames()

	local masterSql =  [[SELECT albums.docId, albums.name, count( DISTINCT r.docId ) FROM
					renditionRevisions as r
				INNER JOIN album_asset ON album_asset.assetId = r.assetId
				INNER JOIN albums ON albums.docId = album_asset.albumId AND albums.useOffline = 1
				LEFT JOIN space s ON s.docId = albums.spaceId
				LEFT JOIN space_user su ON s.spaceUserId = su.fullDocId
				WHERE
					( albums.spaceId IS NULL OR su.role == 'editor' ) AND renditionName IN CARRAY(?,?,'char*')
					OR ( albums.spaceId IS NOT NULL AND ( su.role IS NULL OR su.role != 'editor' ) AND renditionName IN CARRAY(?,?,'char*') )
				]]

	local proxySql = [[SELECT albums.docId, albums.name, count( DISTINCT r.docId ) FROM
					renditionRevisions as r
				INNER JOIN album_asset ON album_asset.assetId = r.assetId
				INNER JOIN albums ON albums.docId = album_asset.albumId and albums.useOffline = 1
				WHERE
					renditionName IN CARRAY(?,?,'char*')
				]]


	local queryArgs

	if binaryDownloadStrategy == LrmConfig.StrategyPreferMaster then
		queryArgs = {
			sql = masterSql,
			calm = 0.25,
			masterRenditionNames,
			#masterRenditionNames,
			proxyRenditionNames,
			#proxyRenditionNames
		}
	else
		queryArgs = {
			sql = proxySql,
			calm = 0.25,
			proxyRenditionNames,
			#proxyRenditionNames
		}
	end

	local progress = self._catalog:indexStore():query( queryArgs )
		:map( function( rows )

			local downloadingAlbums = {}

			for _, row in ipairs( rows ) do

				if row[ 1 ] then
					-- map from album id to album name and count
					downloadingAlbums[ row[ 1 ] ] = {
						albumName = row[ 2 ],
						count = row[ 3 ]
					}
				end
			end
			
			return downloadingAlbums

		end )

	return {
		value = progress,
	}

end

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

function LriSyncStatusModel.makeModel( catalog )

	assert( catalog )

	local uploadingToOzProgress = getUploadProgress( catalog )

	return {
		_catalog = catalog,

		value = {
			isUploading = catalog:getSyncClient():isPushingMetadata(),
			isDownloading = catalog:getSyncClient():isPullingMetadata(),
			pendingUploadsToOz = uploadingToOzProgress,
			progressBinaryUploads = getDetailedUploadProgress( catalog ),
			estimatedTimeRemainingForUploads = catalog:getSyncClient():getEstimatedTimeRemainingForUploads()
		},

		models = Model,

		events = {
		},

		close = function( self )


		end
	}

end

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

return LriSyncStatusModel
