/***********************************************************************/
/*                                                                     */
/*                      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.                                    */
/*                                                                     */
/***********************************************************************/

function RemoteContentStorage(/*[String]*/ inCacheBasePath, /*[String]*/ inBaseURL)
{
	var cacheBasePath = inCacheBasePath;
 	var cache = (isValidProperty(inCacheBasePath) ? new LocalCacheContentStorage(inCacheBasePath) : new MemoryContentStorage());
 	var baseURL = inBaseURL;
 	var fileCaching = isValidProperty(inCacheBasePath);
 
	//////////////////////////////////////////////////////////////////////////////
	//
	// Return absolute url of content file
	//
	this.getURL = function(/*[string]*/ inWorkflowID, /*[string]*/ inContentID)
	{
		var workflowID = inWorkflowID;
		var contentID = inContentID;

		var job = cache.getURL(workflowID, contentID);

		if (!job.isStatus(IJob.STATUS_SUCCESS))
		{
			// check if localized url exists
			//
			var url = getContentURL(workflowID, contentID, true);

			function urlFilter()
			{
				// url exists, cache and return it
				//
				cache.setURL(workflowID, contentID, url);
				dbgLogContent("RemoteContentStorage.getURL", workflowID, contentID, url);
				return url;
			}

			job = new ConditionalJob(new JobCondition(new HTTPExistsJob(url, urlFilter), null, function()
			{
				// check if not localized url exists
				//
				url = getContentURL(workflowID, contentID, false);

				return new JobCondition(new HTTPExistsJob(url, function()
				{
					// url exists, cache and return it
					//
					cache.setURL(workflowID, contentID, url);
					dbgLogContent("RemoteContentStorage.getURL", workflowID, contentID, url);
					return url;
				},
				function ()
				{
					return "RemoteContentStorage.getURL '" + workflowID + "' / '" + contentID + "' NOT exist";
				}));
			}));
		}

		return job;
	}
 
	//////////////////////////////////////////////////////////////////////////////
	//
	// Return content as it is (e.g. raw text is returned as raw text, html is returned as html, etc.)
	//
	this.getRaw = function(/*[string]*/ inWorkflowID, /*[string]*/ inContentID)
	{
		var workflowID = inWorkflowID;
		var contentID = inContentID;

		var job = cache.getRaw(workflowID, contentID);

		if (!job.isStatus(IJob.STATUS_SUCCESS))
		{
			// check if localized content exists
			//
			var url = getContentURL(workflowID, contentID, true);

			job = new ConditionalJob(new JobCondition(new HTTPExistsJob(url), function()
			{
				dbgLogContent("RemoteContentStorage.getRaw", workflowID, contentID, url);

				return new JobCondition(new HTTPGetJob(url, function(/*[XMLHttpRequest]*/ inRequest)
				{
					var ret = inRequest.responseText;
					cache.setRaw(workflowID, contentID, ret);
					return ret;
				}));
			},
			function()
			{
				// check if not localized url exists
				//
				url = getContentURL(workflowID, contentID, false);

				return new JobCondition(new HTTPExistsJob(url, null, function()
				{
					// Error filter
					return "RemoteContentStorage.getURL '" + workflowID + "' / '" + contentID + "' NOT exist";
				}),
				function()
				{
					// Result condition
					dbgLogContent("RemoteContentStorage.getRaw", workflowID, contentID, url);

					return new JobCondition(new HTTPGetJob(url, function (/*[XMLHttpRequest]*/ inRequest)
					{
						var ret = inRequest.responseText;
						cache.setRaw(workflowID, contentID, ret);
						return ret;
					}));
				});
			}));
		}

		return job;
	}
 
	//////////////////////////////////////////////////////////////////////////////
	//
	// Return content from string table
	//
	this.getString = function(/*[string]*/ inWorkflowID, /*[string]*/ inContentID)
	{
		var workflowID = inWorkflowID;
		var contentID = inContentID;

		var job = cache.getString(inWorkflowID, inContentID);

		if (!job.isStatus(IJob.STATUS_SUCCESS))
		{
			function createStringtableJob(/*[String]*/ inStringtableData, /*[String]*/ inURL)
			{
				var stringtable = new StringTable();
				stringtable.setData(inStringtableData);
				cache.setStringtable(workflowID, stringtable);
				var str = stringtable.getString(contentID);
				var stringtableJob = new Job();

				if (isValidProperty(str))
				{
					stringtableJob.setResult(str);
					dbgLogContent("RemoteContentStorage.getString", workflowID, contentID, inURL);
				}
				else
				{
					stringtableJob.setError("RemoteContentStorage.getString '" + workflowID + "' / '" + contentID + "' NOT exist");
					dbglogError(stringtableJob.getError());
				}

				return stringtableJob;
			}

			// check if localized content exists
			//
			var url = getContentURL(workflowID, StringTable.FILENAME, true);

			job = new ConditionalJob(new JobCondition(new HTTPExistsJob(url), function()
			{
				return new JobCondition(new HTTPGetJob(url, null, function()
				{
					// Error filter
					return "RemoteContentStorage.getString '" + workflowID + "' / '" + contentID + "' NOT exist";
				}),
				function(/*[XMLHttpRequest]*/ inRequest)
				{
					// Result condition
					return new JobCondition(createStringtableJob(inRequest.responseText, url));
				});
			},
			function()
			{
				// check if NOT localized content exists
				//
				url = getContentURL(workflowID, StringTable.FILENAME, false);

				return new JobCondition(new HTTPExistsJob(url, null, function()
				{
					// Error filter
					return "RemoteContentStorage.getString '" + workflowID + "' / '" + contentID + "' NOT exist";
				}),
				function()
				{
					// Result condition
					return new JobCondition(new HTTPGetJob(url, null, function()
					{
						// Error filter
						return "RemoteContentStorage.getString '" + workflowID + "' / '" + contentID + "' NOT exist";
					}),
					function(/*[XMLHttpRequest]*/ inRequest)
					{
						// Result condition
						return new JobCondition(createStringtableJob(inRequest.responseText, url));
					});
				});
			}));
		}

		return job;
	}
	
	// private ///////////////////////////////////////////////////////////////////
	
	//////////////////////////////////////////////////////////////////////////////
	//
	// Create remote url for content
	//
	function getContentURL(/*[string]*/ inWorkflowID, /*[string]*/ inContentID, /*[Boolean]*/ inLocalized)
	{
		var url = '';
		
		if (inContentID.indexOf('http') == 0)
		{
			url = inContentID;
			
			if (inLocalized)
			{
				var pos = url.lastIndexOf('/');
				
				if (pos >= 0)
				{
					var tmp = url.substring(0, pos);
					tmp += '/';
					tmp += getLocale();
					tmp += url.substring(pos);
					url = tmp;
				}
			}
		}
		else
		{
			url = baseURL + inWorkflowID + '/';
			
			if (inLocalized)
			{
				url += getLocale() + '/';
			}

			url += inContentID;
		}

		dbgLogContent("RemoteContentStorage.getContentURL", inWorkflowID, inContentID, url);
		
		return url;
	}
	
	//////////////////////////////////////////////////////////////////////////////
	//
	// Initialize
	//
	(function()
	{
		var res = cep.fs.stat(inCacheBasePath);
	
		if (isValidProperty(res) && res.err != cep.fs.NO_ERROR)
		{
			cep.fs.makedir(inCacheBasePath);
		}
	})();
}