/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2015 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.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, node: true */
/*global dw, DWfile, DWUri, dwscripts*/

(function () {
	"use strict";

	// In this file, directory URLs do not have '/' at the end.
	var updatesDirURL = dw.getUserConfigurationPath() + "Updates";
	var updatesPropertiesFileURL = updatesDirURL + "/Iam/Strings/updatesInfo.properties";
	var patchPropertiesFileURL = updatesDirURL + "/Iam/Strings/patchInfo.properties";
    var prefsSection = "Updates";
	var lastShownNotificationId = "Last Shown Notification Id";
	var nodeArgs = [];
	var nodeURL;

	function _shouldCheckUpdates() {
		// If install.xml exists, it means previously downloaded updates
		// are not yet installed, so do not check for new updates.
		var installXmlURL = updatesDirURL + "/Install/install.xml";
		if (DWfile.exists(installXmlURL, false)) {
			return false;
		}
		return true;
	}

	function _toPath(url) {
		var uri = new DWUri(url);
		var path = (dwscripts.IS_WIN ? uri.toLocalPath() : uri.toLocalPathUnix());
		return path;
	}

	function _toUrl(path) {
		return dwscripts.filePathToLocalURL(path);
	}

	// Get id of the latest successfully installed update.
	function _getCurrentUpdateId() {
		var uninstallXmlURL = updatesDirURL + "/Uninstall/uninstall.xml";
		var uninstallDOM;
		var updateNodes;
		var latestUpdate;
		var id;

		if (!DWfile.exists(uninstallXmlURL, false)) {
			return "0";
		}

		uninstallDOM = dw.getDocumentDOM(uninstallXmlURL);
		if (!uninstallDOM) {
			return "0";
		}

		updateNodes = uninstallDOM.getElementsByTagName("update");

		if (updateNodes && updateNodes.length > 0) {
			id = updateNodes[updateNodes.length - 1].getAttribute("id");
			if (id) {
				return id;
			}
		}
		return "0";
	}

	// Get id of the latest shown notification Id
	function _getCurrentNotificationId() {
		var notificationIdStr = dw.getPreferenceString(prefsSection, lastShownNotificationId, "0");
		return notificationIdStr;
	}

	function _populateNodeArgs() {

		// first argument is script path
		var quote = dwscripts.IS_WIN ? "\"" : "";
		var scriptPath = _toPath(updatesDirURL + "/Core/Node/download.js");
		nodeArgs.push(quote + scriptPath + quote);

		// arguments to the script
		nodeArgs.push("locale=" + dw.getAppLanguage());
		nodeArgs.push("os=" + (dwscripts.IS_WIN ? "win" : "mac"));
		nodeArgs.push("currentUpdateId=" + _getCurrentUpdateId());
		nodeArgs.push("currentNotificationId=" + _getCurrentNotificationId());
		nodeArgs.push(quote + "updatesDir=" + _toPath(updatesDirURL) + quote);
		nodeArgs.push("download=updates");

		// dw.appVersion => major.minor.dotminor.build
		var appVersion = dw.appVersion.split(" ")[0];
		if (appVersion.split(".").length === 4) {
			// appVersion => major.minor.dotminor
			appVersion = appVersion.split(".").slice(0, -1).join(".");
		}

		nodeArgs.push("appVersion=" + appVersion);
		nodeArgs.push("coreVersion=v1"); // Revision of core logic of "Updates"
	}

	function _cleanupPreLaunch() {
		DWfile.remove(updatesPropertiesFileURL);
		DWfile.remove(patchPropertiesFileURL);
	}

	// 1. Check if new updates should be checked
	if (!_shouldCheckUpdates()) {
		return;
	}

	// 2. Get local URL of node
    var rootDirURL = _toUrl(dw.getRootDirectory());
	if (dwscripts.IS_MAC) {
        nodeURL = rootDirURL + dw.appName + ".app/Contents/MacOS/node";
        if (!DWfile.exists(nodeURL, false)) {
            nodeURL = rootDirURL + "Dreamweaver.app/Contents/MacOS/node";
            if (!DWfile.exists(nodeURL, false)) {
                return;
            }
        }
	} else {
        nodeURL = rootDirURL + "node/node.exe";
        if (!DWfile.exists(nodeURL, false)) {
            return;
        }
    }

	// 3. Populate node args
	_populateNodeArgs();

	// 4. Cleanup files before launching node
	_cleanupPreLaunch();

	// 5. Launch node
	dw.createProcess(nodeURL, nodeArgs);
}());
