﻿/*************************************************************************
*
* ADOBE CONFIDENTIAL 
* ___________________
*
*  Copyright 2010 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 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.
**************************************************************************/
// Constants and variables for handling remote repairs
var INDESIGN = "ID";

var TIME_TO_WAIT = 100;
var PARTIAL_SUCCESS_RETVAL = 'partialSuccess';
var FAILURE_RETVAL = 'failure';

var callSourceApplicationToRepair = function(args) {
    return ReviewPanelUtilities.callMainFunction(_callSourceApplicationToRepair, args);
}

var _callSourceApplicationToRepair = function(args) {
	var retval = '<error />'; 
	var arguments = new XML(args);
    // Store the passed arguments
    var sourceApp = arguments.@appName.toString();
    var docId = arguments.@documentId;
    var fileURL = arguments.@filePath.toString();
    var rootVolume = arguments.@rootVolumeName.toString();
    fileURL = ReviewPanelUtilities.fixPathIfNeeded(fileURL, 1);
    fileURL = ReviewPanelUtilities.fixVolumeIfNeeded(fileURL, rootVolume);
    // Fetch the application specifier for the source app
    var appSpecifier = BridgeTalk.getSpecifier(appNames[sourceApp]);
    
    // Check if the application specifier is valid
    if (appSpecifier != null && appSpecifier != 'undefined') {
    	// Get the status of the host application
        var status = BridgeTalk.getStatus (appSpecifier);
        if (status != 'ISNOTINSTALLED' && status != 'BUSY' && status != 'UNDEFINED') {
        	// The valid status's are - ISNOTRUNNING, IDLE, PUMPING.
        	// Create a bridgetalk object aimed at the necessary app
            var bt = new BridgeTalk;
            bt.target = appSpecifier;
            bt.body = appScripts[sourceApp] + " repairAssociation('"+fileURL+"', '"+PARTIAL_SUCCESS_RETVAL+"', '"+FAILURE_RETVAL+"', '"+docId+"');";
            bt.onResult = function(msg) {
            	// Repair worked :)
                var btResult = msg.body;
                if (btResult != FAILURE_RETVAL)
                {
            		if (btResult != PARTIAL_SUCCESS_RETVAL) {
            			retval = new XML('<success />');
		                var returnId = new XML('<instance id="'+btResult+'"/>');        
		                retval.appendChild(returnId);
	                }
	                else {
	                	retval = '<success />'; 
	                }
            	}
            }
            bt.onReceived = function (msg) {
               // alert ("received");
            }
            bt.onError = function(msg) {
                // alert ("error "+msg.body);
            }
            bt.onTimeout = function (msg) {
                // not sure what to do here. The request can time out because the app took a while to launch.
                // This doesn't necessarily mean that the request won't complete.
                // A solution will be to increase the value of TIME_TO_WAIT so that we do not get false negatives. 
          		// TO-DO.
                // alert ("time out");
            }
            bt.send(TIME_TO_WAIT);
        }
	}
    
    return retval;
}


var repairScriptID = "\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage) {\
	    var retval = failureMessage;\
	    var output;\
	    var doc = null;\
		var myFile = File(fileURL);\
		try {\
			doc = app.open (myFile);\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
	    if (doc != null) {\
	    	try {\
	        	var instanceId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'InstanceID');\
	        	instanceId = instanceId.split(':').pop();\
	        	retval = instanceId;\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

// Maintain an array for the app names
var appNames = new Array();
appNames[INDESIGN] = "indesign";

// Maintain an array for the script which should be executed for a particular product
var appScripts = new Array();
appScripts[INDESIGN] = repairScriptID;

/**
 * escapeFilePath enters escape sequences for &, <, "
 * We cannot use these strings as attribute values
 */
function escapeFilePath(filePath) {
	try {
		filePath = filePath.replace(/&/g, "&amp;");
		filePath = filePath.replace(/"/g, "&quot;");
		filePath = filePath.replace(/</g, "&lt;");
		return filePath;
	}
	catch (e) {
		return filePath;	
	}
}
