﻿/*************************************************************************
*
* 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 PHOTOSHOP = "PS";
var ILLUSTRATOR = "IL";
var PREMIEREPRO = "PP";
var DREAMWEAVER = "DW";
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;
            // DreamWeaver has its own custom code to fix the url
		    if (sourceApp == DREAMWEAVER) {
		    	var tempFile = File (fileURL);
		    	bt.body = appScripts[sourceApp] + " repairAssociation('"+fileURL+"', '"+tempFile.fsName+"', '"+PARTIAL_SUCCESS_RETVAL+"', '"+FAILURE_RETVAL+"', '"+docId+"');";
		    }
		    else
            	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;
}
// checkPPStatus returns false if Premiere Pro is busy or not installed.
function checkPPStatus() {
	var appSpecifier = BridgeTalk.getSpecifier(appNames[PREMIEREPRO]);
	// 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 == 'ISNOTRUNNING' || status != 'IDLE' || status != 'PUMPING') {
        	// The valid status's are - ISNOTRUNNING, IDLE, PUMPING.
        	return true;
    	}
    }
    return false;
}

// openPProProjectSequence: open specified project and sequence using premiere pro

function openPProProjectSequence(path, sequenceId) {
	ppro = new BridgeTalk();
	var appSpecifier = BridgeTalk.getSpecifier(appNames[PREMIEREPRO]);
	ppro.target = appSpecifier;
	ppro.body = appScripts[PREMIEREPRO] + " repairAssociation('"+path+"', '"+PARTIAL_SUCCESS_RETVAL+"', '"+FAILURE_RETVAL+"', '"+sequenceId+"');";
    ppro.onResult = function(msg) {
        var btResult = msg.body;
        if (btResult == FAILURE_RETVAL)
        {
    		return false;
    	}
    }
    ppro.onError = function(msg) {
        // alert ("error "+msg.body);
        return false;
    }
    ppro.onTimeout = function (msg) {
        //return false;
    }
    ppro.send(TIME_TO_WAIT);
	return true;
}

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;\
    }\
";

var repairScriptPS = "\
    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 metadata = new XML(doc.xmpMetadata.rawData);\
				var id = metadata.descendants('xmpMM:InstanceID')[0].toString();\
				retval = id.split(':').pop();\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

var repairScriptIL = "\
    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 metadata = new XML(doc.XMPString);\
				var id = metadata.descendants('xmpMM:InstanceID')[0].toString();\
				retval = id.split(':').pop();\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

var repairScriptPP = "\
	function fixProjectPath(path) {\
		if(File.fs == 'Windows')\
		{\
			path = path.replace (/\\/g, '/');\
			if(path.indexOf('//?/') == 0) {\
				path = path.substring(4);\
				if (path.indexOf('UNC') == 0) {\
					path = '/' + path.substring(3);\
				}\
			}\
		}\
		return path;\
	}\
	function isProjectOpen(path) {\
		try {\
		var projPath = app.project.path;\
		projPath = fixProjectPath(projPath);\
		var pFile = File(projPath);\
		var nFile = File(path);\
		if(pFile.exists && nFile.exists && pFile.fsName == nFile.fsName)\
			return true;\
		}\
		catch(e) {\
		\
		}\
		return false;\
	}\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage, docId) {\
	    var retval = failureMessage;\
	    var output;\
		var myFile = File(fileURL);\
		try {\
			if (!isProjectOpen(fileURL)){\
				if (!app.openDocument(myFile.fsName)){\
					if(myFile.execute())\
				    	retval = partialSuccessMessage;\
					else\
						retval = failureMessage;\
				}else{\
					app.project.openSequence(docId);\
				}\
			}\
			else {\
				app.project.openSequence(docId);\
			}\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
        retval = docId;\
	    return retval;\
    }\
";

var repairScriptDW = "\
	function repairAssociation(fileURL, dwURL, partialSuccessMessage, failureMessage, docId) {\
		var retval = failureMessage;\
		if (DWfile.exists(dwURL)) {\
			var doc = dreamweaver.openDocument(dw.convertURIToFilePath(dwURL));\
			if (doc == null || doc == undefined) {\
				if(dreamweaver.openFileInOSDefaultApp(fileURL)) {\
	        		retval = partialSuccessMessage;\
	        	}\
				else {\
					retval = failureMessage;\
				}\
			}\
			else {\
				try {\
					retval = doc.getOpenPathName();\
				} catch (e) {\
					retval = partialSuccessMessage;\
				}\
			}\
		}\
		// TO-DO - return is not supported in DW.\
		//return 'abc';\
	}\
";

// Maintain an array for the app names
var appNames = new Array();
appNames[INDESIGN] = "indesign";
appNames[PHOTOSHOP] = "photoshop";
appNames[ILLUSTRATOR] = "illustrator";
appNames[PREMIEREPRO] = "premierepro";
appNames[DREAMWEAVER] = "dreamweaver";

// Maintain an array for the script which should be executed for a particular product
var appScripts = new Array();
appScripts[INDESIGN] = repairScriptID;
appScripts[PHOTOSHOP] = repairScriptPS;
appScripts[PREMIEREPRO] = repairScriptPP;
appScripts[ILLUSTRATOR] = repairScriptIL;
appScripts[DREAMWEAVER] = repairScriptDW;

/**
 * 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;	
	}
}
