(function() {

function install(){
	fl.outputPanel.clear();
	fl.trace("Installing Slugline...");
	// install the bundle to the user's config
	var config = fl.configURI;
	
	var externalLibsDir = config + "External%20Libraries/";
	
	var toolsDir = config + "tools/";
	
	var scriptPath = fl.scriptURI;
	var scriptDir = scriptPath.substring(0, scriptPath.lastIndexOf("/"));
	
	var configExists = FLfile.exists(config);
	var externalLibsDirExists = FLfile.exists(externalLibsDir);
	var toolsDirExists = FLfile.exists(toolsDir);
	
	if (!configExists) {
		fl.trace("Config directory does not exist");
		return;
	}
	
	if (!externalLibsDirExists) {
		fl.trace("External Libraries directory does not exist");
		return;
	}
	
	if (!toolsDirExists) {
		fl.trace("Tools directory does not exist");
		return;
	}

	var projectName = "slugline";
	var bundleName = projectName + ".bundle";
	var toolJsfl = projectName + ".jsfl";
	var toolXml = projectName + ".xml";
	var toolPng = projectName + ".png";

	var projectDir = scriptDir + "/dist/";
	var bundlePath = projectDir + bundleName;
	var toolJsflPath = projectDir + toolJsfl;
	var toolXmlPath = projectDir + toolXml;
	var toolPngPath = projectDir + toolPng;

	


	// check that all the files exist
	var files = [bundlePath, toolJsflPath, toolXmlPath, toolPngPath];
	var fileExists = true;
	for (var i = 0; i < files.length; i++) {
		if (!FLfile.exists(files[i])) {
			fl.trace("File does not exist: " + files[i]);
			fileExists = false;
		}
	}

	if (!fileExists) {
		fl.trace("One or more dist files do not exist, please re-download the project.");
		return;
	}


	var bundleInstallDir = externalLibsDir + bundleName;
	var toolInstallDir = toolsDir + toolJsfl;
	var toolXmlInstallDir = toolsDir + toolXml;
	var toolPngInstallDir = toolsDir + toolPng;
	
	var filemap = [
		[bundlePath, bundleInstallDir],
		[toolJsflPath, toolInstallDir],
		[toolXmlPath, toolXmlInstallDir],
		[toolPngPath, toolPngInstallDir]
	];

	var copiedFiles = [];

	
	for (var i = 0; i < filemap.length; i++) {
		if (FLfile.exists(filemap[i][0])) {
			if (FLfile.exists(filemap[i][1])) {
				FLfile.remove(filemap[i][1]);
			}
			var success = FLfile.copy(filemap[i][0], filemap[i][1]);
			if (success) {
				copiedFiles.push(filemap[i][1]);
			} else {
				fl.trace("Failed to copy file: " + filemap[i][0] + " to " + filemap[i][1]);
				break;
			}
		} else {
			fl.trace("File does not exist: " + filemap[i][0] + " to " + filemap[i][1]);
		}
	}

	//remove the files that were copied if any failed to copy
	if (copiedFiles.length != filemap.length) {
		for (var i = 0; i < copiedFiles.length; i++) {
			FLfile.remove(copiedFiles[i]);
		}
		fl.trace("Install failed, please try again.");
		return;
	}

	fl.trace("Slugline installed successfully!");
	fl.trace("Please restart Adobe Animate to use the tool.");
}

install();

})();