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

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'

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

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


local derefOpt = KSTableUtils.derefOpt

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

local LrmSyncStatusModel = {}
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 )

	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:makeBinaryDownloadProgressModel( 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 masterSql =  [[SELECT 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 ( 'thumbnail2x', 'preview', 'proxyWithoutMaster', 'master', 'xmp_develop' )
					OR ( albums.spaceId IS NOT NULL AND ( su.role IS NULL OR su.role != 'editor' ) AND renditionName IN ( 'thumbnail2x', 'preview', 'proxy', 'xmp_develop' ) )
				]]

	local proxySql = [[SELECT 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 ( 'thumbnail2x', 'preview', 'proxy', 'xmp_develop' )
				]]


	local sql

	if binaryDownloadStrategy == LrmConfig.StrategyPreferMaster then
		sql = masterSql
	else
		sql = proxySql
	end

	if binaryDownloadStrategy == LrmConfig.StrategyPreferMaster then
		sql = string.format( sql, "( 'thumbnail2x', 'preview', 'proxyWithoutMaster', 'master' )" )
	else
		sql = string.format( sql, "( 'thumbnail2x', 'preview', 'proxy' )" )
	end

	local progress = self._catalog:indexStore():query{ 
			sql = sql,
			calm = 0.25,
			singleColumnQuery = true,
		}
		:pluck( 1 )


	return {
		value = progress,
	}

end

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

function Model:makeBinaryDownloadProgressAndAlbumModel( binaryDownloadStrategy )

	binaryDownloadStrategy = binaryDownloadStrategy or LrmConfig.StrategyPreferProxy

	local masterSql =  [[SELECT 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 ( 'thumbnail2x', 'preview', 'proxyWithoutMaster', 'master', 'xmp_develop' )
					OR ( albums.spaceId IS NOT NULL AND ( su.role IS NULL OR su.role != 'editor' ) AND renditionName IN ( 'thumbnail2x', 'preview', 'proxy', 'xmp_develop' ) )
				]]

	local proxySql = [[SELECT 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 ( 'thumbnail2x', 'preview', 'proxy', 'xmp_develop' )
				]]

	local sql

	if binaryDownloadStrategy == LrmConfig.StrategyPreferMaster then
		sql = masterSql
	else
		sql = proxySql
	end


	local progress = self._catalog:indexStore():query{ 
			sql = sql,
			calm = 0.25
			
		}
		:map( function( rows )

			return { 
				album = rows[ 1 ][ 1 ], 
				count = rows[ 1 ][ 2 ] }

		end )


	return {
		value = progress,
	}

end

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

function LrmSyncStatusModel.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 LrmSyncStatusModel
