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

//////////////////////////////////////////////////////////////////////////////
//
// Replace content symbols with actual strings
//
function replaceStringSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage)
{
	return replaceSymbols(["${", "}$"], inStorage.getString, inContent, null);
}

function replaceURLSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage)
{
	return replaceSymbols(["#{", "}#"], inStorage.getURL, inContent, null);
}

function replaceAllSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage)
{
	var storage = inStorage;
	
	function doReplaceStringSymbols(/*[String]*/ inContent)
	{
		return replaceStringSymbols(inContent, storage);
	}

	function doReplaceURLSymbols(/*[String]*/ inContent)
	{
		return replaceURLSymbols(inContent, storage);
	}
	
	return new SequenceJob([doReplaceStringSymbols, doReplaceURLSymbols], inContent);
}

function replaceWorkflowStringSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage, /*[String]*/ inWorkflowID)
{
    return replaceSymbols(["${", "}$"], inStorage.getString, inContent, inWorkflowID);
}

function replaceWorkflowURLSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage, /*[String]*/ inWorkflowID)
{
    return replaceSymbols(["#{", "}#"], inStorage.getURL, inContent, inWorkflowID);
}

function replaceWorkflowDataSymbols(/*[String]*/ inContent, /*[String]*/ inWorkflowID)
{
	return replaceSymbols(["%{", "}%"], getSymbolData, inContent, inWorkflowID);
}

function replaceWorkflowAllSymbols(/*[String]*/ inContent, /*[IContentStorage]*/ inStorage, /*[String]*/ inWorkflowID)
{
	var storage = inStorage;
	var workflowID = inWorkflowID;

	function doReplaceStringSymbols(/*[String]*/ inContent)
	{
		return replaceWorkflowStringSymbols(inContent, storage, workflowID);
	}

	function doReplaceURLSymbols(/*[String]*/ inContent)
	{
		return replaceWorkflowURLSymbols(inContent, storage, workflowID);
	}

	function doReplaceDataSymbols(/*[String]*/ inContent)
	{
		return replaceWorkflowDataSymbols(inContent, workflowID);
	}

	return new SequenceJob([doReplaceStringSymbols, doReplaceURLSymbols, doReplaceDataSymbols], inContent);
}

function replaceSymbols(/*[Array]*/ inDelimter, /*[Function]*/ inContentFunction, /*[String]*/ inContent, /*[String]*/ inWorkflowID)
{
    var job = new Job();
    var intro = inDelimter[0];
    var tail = inDelimter[1];
    var workflowID = inWorkflowID;
    var ret = inContent;
    var contentFct = inContentFunction;

    var part1 = '';
    var part2 = '';
    var startPos = -1;
    var endPos = -1;

    function insertSymbolContent(/*[String]*/ inSymbolContent)
    {
        ret = part1 + inSymbolContent + part2;
        startPos = ret.indexOf(intro);

        findNextSymbol();
    }

    function findNextSymbol()
    {
        startPos = ret.indexOf(intro);
        endPos = ret.indexOf(tail);

        if (startPos >= 0 && endPos > 0)
        {
            part1 = ret.substring(0, startPos);
            part2 = ret.substring(endPos + tail.length);

            var symbol = ret.substring(startPos + intro.length, endPos);

            if (symbol.length)
            {
                var contentJob = contentFct(workflowID, symbol);
				contentJob.wait(function(/*[String]*/ inResult)
				{
					insertSymbolContent(inResult);
				},
				function(/*[String]*/ inError)
				{
					job.setError(inError);
				});
            }
            else
            {
                insertSymbolContent('');
            }
        }
        else
        {
            job.setResult(ret);
        }
    }

    findNextSymbol();

	return job;
}

//////////////////////////////////////////////////////////////////////////////
//
// Get data for symbol
//
function getSymbolData(/*[String]*/ inWorkflowID, /*[String]*/ inSymbol)
{
	var job = new Job();

	switch (inSymbol)
	{
		case 'CONTENT_ROOT':
		{
			var localroot = getOnBoardingFolder(true) + 'Content/';
			var res = cep.fs.stat(localroot + inWorkflowID);
			var isLocal = (isValidProperty(res) && res.data.isDirectory() && res.err == cep.fs.NO_ERROR);

			if (!isLocal)
			{
				localroot = getOnBoardingFolder(false) + 'Content/';
				res = cep.fs.stat(localroot + inWorkflowID);
				isLocal = (isValidProperty(res) && res.data.isDirectory() && res.err == cep.fs.NO_ERROR);
			}

			if (isLocal)
			{
				job.setResult(localroot);
			}
			else
			{
				job.setResult(REMOTE_URL_RELEASE);
			}
		}
		break;

		case 'WORKFLOW_ROOT':
		{
			// We are looking for the content folder first, if found we know
			// where the workflows folder ist located
			//
			var localroot = getOnBoardingFolder(true) + 'Content/';
			var localwfroot = getOnBoardingFolder(true) + 'Workflows/';
			var res = cep.fs.stat(localroot + inWorkflowID);
			var isLocal = (isValidProperty(res) && res.data.isDirectory() && res.err == cep.fs.NO_ERROR);

			if (!isLocal)
			{
				localroot = getOnBoardingFolder(false) + 'Content/';
				localwfroot = getOnBoardingFolder(false) + 'Workflows/';
				res = cep.fs.stat(localroot + inWorkflowID);
				isLocal = (isValidProperty(res) && res.data.isDirectory() && res.err == cep.fs.NO_ERROR);
			}

			if (isLocal)
			{
				job.setResult(localwfroot);
			}
			else
			{
				job.setResult(REMOTE_URL_RELEASE);
			}
		}
		break;

		case "LOCALE":
		{
			job.setResult(getLocale());
		}
		break;

		case "PLATFORM":
		{
			job.setResult(getPlatform());
		}
		break;
	}

	return job;
}

//////////////////////////////////////////////////////////////////////////////
//
// Get current locale
//
function getLocale()
{
    var cs = new CSInterface();
    var env = cs.getHostEnvironment();
    return env.appUILocale;
}

//////////////////////////////////////////////////////////////////////////////
//
// Debug logging
//
function dbgLogWorkflows(/*[String]*/ inFunction, /*[String]*/ inText, /*[Array]*/ inWorkflows)
{
    var idStr = '';

    forEach(inWorkflows, function(workflow)
    {
        if (isValidProperty(workflow))
        {
            if (isValidProperty(workflow.name))
            {
                idStr += workflow.name + ' ';
            }
            if (isValidProperty(workflow.id))
            {
                idStr += '[' + workflow.id + ']';
            }
        }
        idStr += ', ';
    });

    dbglogInfo(inFunction + ' ' + inText + ': ' + idStr);
}

function dbgLogContent(/*[String]*/ inFunction, /*[String]*/ inWorkflowID, /*[String]*/ inContentID, /*[String]*/ inText)
{
    var logStr = '';

    if (isValidProperty(inFunction))
    {
        logStr += inFunction + ' ';
    }

    logStr += '[' + inWorkflowID + ', ' + inContentID + ']';
    logStr += ' : ' + inText;
    dbglogInfo(logStr);
}