/**
 * Created by rockyl on 2019-11-25.
 */

var mergeFlagReg = /__m/;
var excludeFlagReg = /__e/;
var extName = '.psd';

var oldDocument = app.activeDocument;

var mergeLayers = [];

var document = oldDocument.duplicate(oldDocument.name.replace(extName, '') + '-合并' + extName, 0);

function traverse(layer, callback) {
	if (layer.layers) {
		for (var i = 0, li = layer.layers.length; i < li; i++) {
			var childLayer;
			try {
				childLayer = layer.layers[i];
			}catch (e) {
				alert('图层[' + layer.name + ']的第' + i + '个子图层存在问题，请先处理掉');
			}
			var action = callback(childLayer);
			switch (action) {
				case 0:
					traverse(childLayer, callback);
					break;
				case 2:
					i--;
					li--;
					break;
			}
		}
	}
}

function deleteDocumentAncestorsMetadata() {
	whatApp = String(app.name);//String version of the app name
	if(whatApp.search("Photoshop") > 0) { //Check for photoshop specifically, or this will cause errors
//Function Scrubs Document Ancestors from Files
		if(!documents.length) {
			alert("There are no open documents. Please open a file to run this script.")
			return;
		}
		if (ExternalObject.AdobeXMPScript == undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
		var xmp = new XMPMeta( activeDocument.xmpMetadata.rawData);
// Begone foul Document Ancestors!
		xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
		app.activeDocument.xmpMetadata.rawData = xmp.serialize();
	}
}

function execute(document) {
	traverse(document, function (layer) {
		if (layer.name.match(mergeFlagReg)) {
			document.activeLayer = layer;

			var newName = layer.name.replace(mergeFlagReg, '');
			layer.name = newName;

			try {
				layer.merge();
				mergeLayers.push(newName);
			}catch (e) {

			}
			return 1;
		} else if (layer.name.match(excludeFlagReg)) {
			try {
				layer.remove();
			}catch (e) {
				alert('移除图层' + layer.name + '失败，可能含有锁的层');
			}
			return 2;
		}
		return 0;
	});

	deleteDocumentAncestorsMetadata();

	document.crop([0, 0, oldDocument.width, oldDocument.height], 0);

	/*if (mergeLayers.length > 0) {
		alert('合并的图层有: ' + mergeLayers.join(','));
	} else {
		alert('没有图层被合并');
	}*/
	alert('整理完成');
}

execute(document);
