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

OzDownloadAccountsTest.lua

2016-06-27
immisch@adobe.com

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

ADOBE CONFIDENTIAL
------------------
Copyright 2016 Adobe Systems Incorporated
All Rights Reserved.

NOTICE: All information contained herein is, and remains 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 are protected by all applicable
intellectual property laws, including trade secret and copyright laws.
Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

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

--[[

	This file downloads the v1 and v2 catalogs from Oz for later testing of the migration.
	(jrechtie: removed v1 support because WFOzDownloadTask is gone.)
	
	It is only of historical interest.

]]--

	
	-- RxLua
local Rx = require 'Rx'

local KSReactive = require "KSReactive"

local WFRxPromiseBridge = require "WFRxPromiseBridge"

local WFAsyncTestCase = require "WFAsyncTestCase"

local WFRxTestCase = require 'WFRxTestCase'

local KSPathUtils = require "KSPathUtils"

local WFArguments = require 'WFArguments'

local KSJsonDecoder = require "KSJsonDecoder"

-- local KSTableUtils = require "KSTableUtils"

local WFLogger = require "WFLogger"

local WFURI = require "WFURI"

local WFCatUser = require "WFCatUser"

local WFCatSpec = require "WFCatSpec"

local WFCatalog = require "WFCatalog"

local WFFileUtils = require "WFFileUtils"

local WFCatMetadataPuller = require "WFCatMetadataPuller"

local WFSQLiteDatabaseImp = require "WFSQLiteDatabaseImp"

local KSLuaUtils = require 'KSLuaUtils'

local hasMigrationTestUsers, MigrationTestUsers = KSLuaUtils.requireIfExists( "MigrationTestUsers" )

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

local asKSPromise = WFRxPromiseBridge

local logger = WFLogger 'OzDownloadAccountsTest'
	:setLevel 'debug'

-- Adjust this
local destination -- = '/Users/lars/Desktop/account-docstores'

-- local derefOpt = KSTableUtils.derefOpt

-- local Observable = Rx.Observable

local check = WFArguments.check

local OzDownloadAccountsTest = {}

local ozV2ServerUrl = 'https://photos.adobe.io'

local ozV1ServerUrl = 'https://api-lr.adbecrsl.com'


local function ozUserFromWFCatUser( wfCatUser )
  		
 	local mockedUser = Rx.Class( 'OzUserFromWFCatUser', {
 	 		
 		getP = function( self, url )
 		
 			return wfCatUser:get( url )
				:call( asKSPromise )
 			
 		end
 		
 	} )()

	return mockedUser

end

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

local function findCatalog( userName, accessToken )

	check( '+string', '+string' )

	local tempSubFolder = KSPathUtils.child( KSPathUtils.getStandardFilePath( 'temp' ),
		userName )

	-- See http://apidocs.adbecrsl.com/v2/docs/multi_page/#method_getaccount
	-- 00000000000000000000000000000000 Derive the account ID from the authorization token.

	local wfUser = WFCatUser( ozV2ServerUrl, '00000000000000000000000000000000', tempSubFolder )

	wfUser:storeTokens( accessToken, 'refreshToken' )

	local accountsUrl = WFURI.resolve( ozV2ServerUrl, '/v2/accounts/00000000000000000000000000000000' )
	
	return wfUser:get( accountsUrl )

		:map( KSJsonDecoder.decodeWebSafeJson )

		:flatMap( function ( account )
		
			local catalogsUrl = WFURI.resolve( ozV2ServerUrl, '/v2/catalogs' )
					
			wfUser:close()
			
			wfUser = WFCatUser( ozV2ServerUrl, account.id, tempSubFolder )
			wfUser:storeTokens( accessToken, 'refreshToken' )
		
			return wfUser:get( catalogsUrl )
				:map( KSJsonDecoder.decodeWebSafeJson )

				:map( function( catalogList )

					for i, resource in ipairs( catalogList.resources ) do
									
						if resource.subtype == 'lightroom' or resource.subtype == 'X-lightroom' then

							logger:infof( string.format( "%s has lightroom catalog %s path = %s", userName, resource.id,
								tempSubFolder ) )
		
							return WFCatSpec( wfUser, resource.id )
						
						end
					
					end

					return nil

				end )
		
		end )

end

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

local function makeV2Downloader( userName, accessToken )

	return function ( rxTest )

		rxTest:setTimeLimit( 2400 )

		local wfCatSpec

		rxTest:expectSingleValue( findCatalog( userName, accessToken )
			:tap( function( _wfCatSpec )
			
				wfCatSpec = _wfCatSpec
			
			end ),
			':ignore:' )

		-- remove the existing v2 catalog
		local dest = string.format( "%s/%s-v2.ozdocstore", destination, userName ) 
		WFFileUtils.delete( dest )
		
		local catalog = 
			WFCatalog( wfCatSpec, wfCatSpec._wfCatUser._path, 
			{
				docStorePath = dest
			} )
		
		local options = {
			isCatalogPuller = true
		}
		
		local puller = WFCatMetadataPuller( catalog, "Test Puller", options )
		
		puller._syncIsStopped = false
		
		rxTest:expectOnlyCompleted( puller:getLatestUpdates() )

		rxTest:expectOnlyCompleted( catalog:docStore():halt() )

		catalog:close()
		
		local db = WFSQLiteDatabaseImp.makeDatabase( dest )
		db:exec('pragma journal_mode=delete')
		db:close()
		
		logger:infof( string.format( 'v2 catalog sync for %s completed', userName ) )
	end

end

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

if destination and WFFileUtils.exists( destination ) then

	for user, token in pairs( MigrationTestUsers ) do
		
		local testname = 'rxTestDownload_' .. string.gsub( user, '[@\.-]', '_' )

		OzDownloadAccountsTest[ testname .. '_v2'  ] = makeV2Downloader( user, token )

	end

end

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

return WFRxTestCase.wrapSuite( OzDownloadAccountsTest )
