var outwitImages = {};

outwitImages.onLoad = function(event) {
  if (window.owLoaded) {
    outwitImages.load(event);
  }
  else {
    window.owOnLoad = outwitImages.load.bind(outwitImages);
  }
};


outwitImages.load = function() {

	//var initialTime = Date.now();

	outwitImages.downloadManager = new coreKit.downloadManager(5);

  try {
    ow.app.load();
  }
  catch(e) {
    ow.log.error("Error loading images", e);
  }

  ow.app.onUnload((function(anEvent) {
    if (outwitImages.downloadManager.pendingCount > 0
        && !ow.app.kernel.prefs.getBool('owImages.dialog.quit.dontAsk', false)) {

      var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
        .getService(Components.interfaces.nsIPromptService);
      var aButtonFlags = (prompts.BUTTON_POS_0) * (prompts.BUTTON_TITLE_IS_STRING) +
        (prompts.BUTTON_POS_1) * (prompts.BUTTON_TITLE_IS_STRING) +
        prompts.BUTTON_POS_1_DEFAULT;
      var returnCheckbox = {value: false};
      var returnVal = prompts.confirmEx(window,
          coreKit.localeService.getString('quitDialogTitle', 'chrome://outwit-modules-images/locale/main.properties'),
          coreKit.localeService.getString('quitDialogText', 'chrome://outwit-modules-images/locale/main.properties'),
          aButtonFlags,
          coreKit.localeService.getString('quitDialogButtonYes', 'chrome://outwit-modules-images/locale/main.properties'),
          coreKit.localeService.getString('quitDialogButtonNo', 'chrome://outwit-modules-images/locale/main.properties'),
          null,
          coreKit.localeService.getString('quitDialogDontAsk', 'chrome://outwit-modules-images/locale/main.properties'),
          returnCheckbox);

      ow.app.kernel.prefs.setBool('owImages.dialog.quit.dontAsk', returnCheckbox.value);
      anEvent.callback((returnVal == 0));
    }
    else {
      anEvent.callback(true);
    }
  }).bind(this));

  ow.app.onShutdown((function(anEvent) {
    outwitImages.downloadManager.unload(true);

    outwitImages.extractControls.unload();
    outwitImages.UIControls.unload();
    outwitImages.browserControls.unload();

    widgets.page.unload();

    mainKit.shutdown();

    this._prefService = Components.classes["@mozilla.org/preferences-service;1"]
      .getService(Components.interfaces.nsIPrefService);
    this._prefService.QueryInterface(Components.interfaces.nsIPrefBranch);
    this._prefService.QueryInterface(Components.interfaces.nsIPrefBranch2);
    this._prefService.removeObserver("", optionsCtrl, false);
    //gBrowser.removeProgressListener(browserListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);

    anEvent.callback();
  }).bind(this));


  try {
    // initialization of the mainKit
    mainKit.init();

    coreKit.timerService.setTimer(50, null, function() {
      if (window.maximize) window.maximize();
      coreKit.timerService.setTimer(200, null, outwitImages.delayedLoad);
    });
  }
  catch(e) {
    ow.log.fatal("Error loading OutWit Images", e);
    ow.app.quit();
  }
};

outwitImages.delayedLoad = function() {
	outwitImages.browserControls.load();
	outwitImages.UIControls.load();
	outwitImages.extractControls.load();

	mainKit.loadURI = outwitImages.browserControls.loadURI;

	// Before loading uri we need to be sure the html is complete, otherwise we lose some pics
	outwitImages.UILoadInterval = setInterval(function(){
		if(document.getElementById("owImagesContainer").thumbs && document.getElementById("owImagesContainer").thumbs._element){
			document.getElementById("owImagesContainer").load();
			clearInterval(outwitImages.UILoadInterval);
		}}, 100);

	document.getElementById('mediacatch').refreshScrollbar();

	window.focus();

  /*
   * XXX TODO REMAKE SIDEGRADE
	mainKit.appUtils.getHub(function(hub) {
		if (!hub) {
			outwitImages.macro.sidegradeDialog();
		}
	});
  */
};



outwitImages.download = function(aBean, aLocation, aRenamePattern) {
	var bean;
	if (aBean.mediaUrl) {
		bean = outwitKit.URLHistoryService.getBeanFromString(aBean.mediaUrl);
	}
	else {
		bean = aBean;
	}
	// XXX compat fix, remove the fourth parameter in next version
	outwitImages.downloadManager.download(bean, aLocation, aRenamePattern, function() {});
};


outwitImages.onGalleryDragOver = function outwitImages_onContainerDragOver(event) {
	var dt = event.dataTransfer;
	var types = dt.types;
	if (types.contains("application/ow-mediaitem")) {
		dt.effectAllowed = "move";
		dt.dropEffect = "move";
		event.preventDefault();
	}
};

outwitImages.onGalleryDrop = function outwitImages_onContainerDrop(event) {
	var dt = event.dataTransfer;
	var types = dt.types;
	if (types.contains("application/ow-mediaitem")) {
		var item = dt.mozGetDataAt("application/ow-mediaitem", 0);
		document.getElementById('mediacatch').removeItem(item);
	}
};


outwitImages.macros = {

	sidegradeDialog: function(manual) {
		function onDialogClose(id, result) {
			Components.utils.import("resource://gre/modules/Services.jsm");
			if (result == "purchase") {
				var browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
				browserWindow.gBrowser.addTab("https://www.outwit.com/products/hub/license.php?version=firefox", null, null, null);
				browserWindow.gBrowser.selectedTab = browserWindow.gBrowser.addTab("https://www.outwit.com/products/hub/buy/current/app/imagesSidegrade", null, null, null);
				browserWindow.focus();
			}
			else if (result == "upgrade") {
				var browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
				browserWindow.gBrowser.selectedTab = browserWindow.gBrowser.addTab("https://www.outwit.com/products/hub/license.php?version=firefox", null, null, null);
				browserWindow.focus();
			}
		}

		if (manual) {
			outwitKit.panelDialogService.showDialog("mkgsidegrademanual", onDialogClose, "focus", "center", {
				"class": "dialog-panel-web",
				template: {
					type: "frame",
					url: "https://www.outwit.com/dialog/dialog.php?dialog=sidegrade_images2hub"
				},
				titleBar: { type: "os", closeButton: true }
			});
		}
		else {
			outwitKit.panelDialogService.showDialog("mkgsidegrade", onDialogClose, "focus", "center", {
				"class": "dialog-panel-web",
				template: {
					type: "frame",
					url: "https://www.outwit.com/dialog/dialog.php?dialog=sidegrade_images2hub"
				},
				titleBar: { type: "os", closeButton: true },
				dontRemind: { type: "count", start: 2, count: 7, hide: true }
			});
		}
	},

  showHelp: function(topic) {
    // XXX SIDEGRADE ?
		// mainKit.appUtils.getHub(function(hub) {
    //  if (!hub) { topic += "-HubMissing"; }
			helpManager.show(topic);
		//});
	},

	createJob: function() {
		this.loadHub();
	},

	loadHub: function() {
    // XXX TO REMAKE
		mainKit.appUtils.getHub(function(hub) {
			if (hub) {
				mainKit.appUtils.loadOutfit(hub, false, widgets.page.browser.currentURI.spec, function(aWin) {
					var [macro, job] = outwitImages.macros.getMacroFromUI();
					aWin.setTimeout(function() {
						aWin.outwitHub.UIControls.loadMacroManager();
						aWin.outwitHub.UIControls.loadJobManager();

						var macroMgr = aWin.document.getElementById("macrosWidget").automatorManager;
						macro.name = macroMgr.getNextName(macro.name);
						macro.checked = "true";
						macroMgr.saveOneAutomator(macro,outwitKit.CONST_AUTOMATOR_CHANGE_NOTHING);
						macroMgr.setActiveAutomator(macro, "true");
						aWin.document.getElementById("macrosWidget").loadMacro(macroMgr.currentAutomator);
						//
						aWin.setTimeout(function() {
							var jobsWidget = aWin.document.getElementById("jobsWidget");
							var jobsMgr = aWin.document.getElementById("jobsWidget").automatorManager;
							jobsWidget.jobEditor.automatorMenulist.reload();
							jobsWidget.jobEditor.currentAutomator = macro;
							jobsWidget.jobEditor.currentName = jobsMgr.getNextName(job.name);
							jobsWidget.saveEditor();
							jobsWidget.automatorManager.setActiveAutomator(jobsWidget.automatorManager.currentAutomator, "false");
							//jobsWidget.automatorManager.dataTree.focus();
						}, 1000);

						/*
						job.name = jobsMgr.getNextName(job.name);
						jobsMgr.setActiveAutomator(job, null);
						*/
						//jobsMgr.saveOneAutomator(job,outwitKit.CONST_AUTOMATOR_CHANGE_NOTHING);

						var buttons = {
							"dontRemind" : { type: "dontRemind", label: coreKit.localeService.getString("dontAskMe.label", "chrome://outwit-kernel/locale/common.properties") },
							"ok": { type: "cancel", label: coreKit.localeService.getString("ok.label", "chrome://outwit-kernel/locale/common.properties") },
							"jobs": { type: "ok", label: coreKit.localeService.getString("widget.label","chrome://outwit-kernel/locale/widgets/jobs/jobs.properties") },
							"macros": { type: "ok", label: coreKit.localeService.getString("widget.label","chrome://outwit-kernel/locale/widgets/macro.properties") }
						};

						function onDialogClose(id, result) {
              if (result == "jobs") {
								aWin.outwitHub.UIControls.showView("jobs");
							}
							else if (result == "macros") {
								aWin.outwitHub.UIControls.showView("macros");
							}
						}

						aWin.outwitKit.panelDialogService.showDialog("newImagesAutomators", onDialogClose, true, "center", {
							"class": "dialog-panel-simple",
				//			modal: true,
							titleBar: { label: coreKit.localeService.getString("hubNewAutomator.title", "chrome://outwit-modules-images/locale/main.properties") },
							template: {
								type: "html",
								data: aWin.outwitKit.panelDialogService.getSimpleDialogTemplate("outwit", coreKit.localeService.getString("hubNewAutomator.message", "chrome://outwit-modules-images/locale/main.properties"))
							},
							buttons: buttons,
							dontRemind: { type: "simple", default: "ok" }
						});

					}, 1000);
				}, window);
			}
			else {
				outwitImages.macros.sidegradeDialog(true);
			}
		});
	},

	getMacroFromUI: function outwitImages_createMacro() {
		//alert(outwitImages.browserControls.initialURI);
		//alert(JSON.stringify(optionsCtrl._optionsPrefs));

		try{


			var currentOptions = {};

			//alert([outwitImages.browserControls.initialURI,typeof(outwitImages.browserControls.initialURI)]);

			currentOptions.initialURI = outwitImages.browserControls.initialURI?outwitImages.browserControls.initialURI:"";
			currentOptions.initialTitle = ow.data.normalization.normalize(outwitImages.browserControls.initialTitle);
			
			for (i=0;i<optionsCtrl._optionsPrefs.length;i++){
				currentOptions[optionsCtrl._optionsPrefs[i][0]] = ow.app.kernel.prefs.get(optionsCtrl._optionsPrefs[i][0]);
			}
			currentOptions["optionsCtrl.autoCatch"] = optionsCtrl.autoCatch;
			currentOptions["optionsCtrl.autoSave"] = optionsCtrl.autoSave;
			currentOptions["optionsCtrl.autoRename"] = optionsCtrl.autoRename;		

			//alert(JSON.stringify(optionsCtrl._optionsPrefs));
			//alert(JSON.stringify(currentOptions).replace(/,/g,',\n'));
			var criteria = ["heightAndWidth","heightOrWidth","height","width"];
			var criterion1 = criteria[Number(currentOptions["oWImages.autocatch.cond1.condition"])];
			var criterion2 = criteria[Number(currentOptions["oWImages.autocatch.cond2.condition"])];
			var comparators = ["greaterOrEqualTo","equalTo","lessOrEqualTo"];
			var comparator1 = comparators[Number(currentOptions["oWImages.autocatch.cond1.comparator"])];
			var comparator2 = comparators[Number(currentOptions["oWImages.autocatch.cond2.comparator"])];
			var size1 = currentOptions["oWImages.autocatch.cond1.size"];
			var size2 = currentOptions["oWImages.autocatch.cond2.size"];

			var sizeCondition = "";

			var urlPattern = ow.app.kernel.prefs.get("oWImages.autocatch.urlpattern")?ow.app.kernel.prefs.get("oWImages.autocatch.urlpattern")+".*":"";
			// XXXXX add heic,heif ?
			var gif = ow.app.kernel.prefs.get("oWImages.autocatch.gif")?"|\\.gif":"";
			var jpg = ow.app.kernel.prefs.get("oWImages.autocatch.jpg")?"|\\.jpe?g":"";
			var png = ow.app.kernel.prefs.get("oWImages.autocatch.png")?"|\\.png":"";
			var extensions = (gif+jpg+png?("("+gif+jpg+png+")").replace(/^\(\|/,"("):"");
			var any = ow.app.kernel.prefs.get("oWImages.autocatch.any");

			urlPattern = !any?urlPattern.replace(/\.(gif|jpe?g|hei[cf]|png|ico|svg|bmp)\s*$/i,""):urlPattern;

			var imageFilter = encodeURIComponent((any ? (urlPattern?"/("+urlPattern+")/i":"") : (urlPattern+extensions?"/("+urlPattern+extensions+")/i":"")).replace(/\\/g,"\\\\")).replace(/\(/g,'%28').replace(/\)/g,'%29');

			// if there is a size condition
			if(size1+size2>-2){
				// if only first size condition
				if(size2 == -1){
					//alert("one condition");
					switch (criterion1){
						case "heightAndWidth":
							sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size1;
							break;
						case "heightOrWidth":
							sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size1+"x";
							break;
						case "width":
							sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x";
							break;
						case "height":
							sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size1;
							break;
						default:
							sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size1;
					}
					// if both size conditions
				} else {
					//alert("two conditions");
					if(comparator1 == comparator2) {
						//alert("one comparator");
						var maxSize = Math.max(size1,size2);
						var minSize = Math.min(size1,size2);
						var size = -1;
						//alert("criterion1+criterion2="+criterion1+criterion2);
						switch (criterion1+criterion2){
							// SUPER UGLY! making arbitrary choices for now (until multiple conditions are possible in the Hub).
							case "heightOrWidth"+"width":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size2+"x";
								break;
							case "heightOrWidth"+"height":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size2;
								break;
							case "width"+"heightOrWidth":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x";
								break;
							case "height"+"heightOrWidth":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size1;
								break;
							case "heightAndWidth"+"width":
							case "heightAndWidth"+"height":
							case "width"+"heightAndWidth":
							case "height"+"heightAndWidth":
								size = /Or/.test(comparator1)?(/greater/.test(comparator1)?"x"+maxSize:"x"+minSize):size1+"x"+size1;
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size;
								break;
							case "width"+"width":
								size = /Or/.test(comparator1)?(/greater/.test(comparator1)?maxSize+"x":minSize+"x"):maxSize+"x";
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size;
								break;
							case "height"+"height":
								size = /Or/.test(comparator1)?(/greater/.test(comparator1)?"x"+maxSize:"x"+minSize):"x"+maxSize;
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size;
								break;
							case "width"+"height":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size2;
								break;
							case "height"+"width":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size2+"x"+size1;
								break;
							default:
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size1;
						}
						//alert ("sizeCondition=\n"+sizeCondition);
					} else {
						// Cannot interpret the two conditions : ignoring the second		
						// Temporary alert for tests TO BE REMOVED!!!!!
						alert("For compatibility reasons, the second\nsize condition will be ignored in the Job.");
						//alert(criterion1);
						switch (criterion1){
							case "heightAndWidth":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size1;
								break;
							case "heightOrWidth":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size1+"x";
								break;
							case "height":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x";
								break;
							case "width":
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue=x"+size1;
								break;
							default:
								sizeCondition = "selectColumn=Size,selectCondition="+comparator1+",selectValue="+size1+"x"+size1;
						}
					}
				}
			}

			var preferencesToSet = "{\"setPreferences\":{"
				                   +(sizeCondition?(imageFilter?"\"filterPattern.images.url\":\""+imageFilter+"\",":""):"")
													 +"\"page.disableJavascript\":"+!currentOptions["oWImages.allowBrowserJavascript"]
													 +(currentOptions["optionsCtrl.autoRename"]?",\"download.autorename.pattern\":\""+currentOptions["oWImages.autorename.pattern"]+"\"":"")
													 +"}}";

			var MAUOptions = "(images=("
						+ (sizeCondition ? sizeCondition+","  : (imageFilter ? "selectColumn=MediaUrl,selectValue="+imageFilter+"," : ""))
						+ (currentOptions["optionsCtrl.autoSave"] ? "download="+currentOptions["optionsCtrl.autoSave"]+"," : "")
						+ "catch=true,background=false"
						    + (!currentOptions["oWImages.autocatch.format.portrait"] ?  ",portrait="+currentOptions["oWImages.autocatch.format.portrait"] : "")
								+ (!currentOptions["oWImages.autocatch.format.landscape"] ? ",landscape="+currentOptions["oWImages.autocatch.format.landscape"] : "")
						+")"
						+ ",actions=(browse=50)"
						+ (!currentOptions["oWImages.autorename.pattern"] ? ",downloads=(fileExists="+(currentOptions["oWImages.autorename.pattern"]?"index":"overwrite")+")" : "")
						+ ")";

			var macro = new outwitKit.automatorClass();

			macro.automatorId =outwitKit.CONST_NEW_AUTOMATOR_ID;

			macro.name = "Images Macro"+(currentOptions.initialTitle?"-"+currentOptions.initialTitle:"");
			macro.kernelVersion = ow.app.kernel.version;
			macro.creationOutfit = "Images";
			macro.automatorType = "macro";
			macro.version = "1.0";
			macro.created = macro.lastModified = ow.util.date.toISO8601(5);

			macro.author = "Generated with OutWit-Images"

			macro.id  = coreKit.stringHelpers.uuid_v4();
			macro.masterId = coreKit.stringHelpers.uuid_v4();
			macro.versionId = coreKit.stringHelpers.uuid_v4();

			macro.url = currentOptions["initialURI"];
			macro.options = preferencesToSet;

			macro.data = "<data>"+
				"<macro><![CDATA[outwit://"+ currentOptions["initialURI"].replace(/^http:\/\//, "") +"&&"+ MAUOptions +"]]></macro>"+
				"<destination>"+
				"<resultsFolder><![CDATA[false]]></resultsFolder>"+
				"<resultsExist><![CDATA[index]]></resultsExist>"+
				"<filesFolder><![CDATA["+ (currentOptions["oWImages.autocatch.autosave.folder"]?currentOptions["oWImages.autocatch.autosave.folder"]:"false") +"]]></filesFolder>"+
				"<filesExist><![CDATA["+(currentOptions["oWImages.autorename.pattern"]?"index":"overwrite")+"]]></filesExist>"+
				"<splitData><![CDATA[]]></splitData>"+
				"</destination>"+
				"<detailedProperties><![CDATA[false]]></detailedProperties>"+
				"</data>";


			var job = new outwitKit.JobAutomator();
			job.automatorId =outwitKit.CONST_NEW_AUTOMATOR_ID;
			job.name = "Images Job"+(currentOptions.initialTitle?"-"+currentOptions.initialTitle:"");
			job.kernelVersion = ow.app.kernel.version;
			job.creationOutfit = "Images";
			job.automatorType = "job";
			job.version = "1.0";
			job.created = job.lastModified = ow.util.date.toISO8601(5);

			job.author = "Generated with OutWit-Images"

			job.id  = coreKit.stringHelpers.uuid_v4();
			job.masterId = coreKit.stringHelpers.uuid_v4();
			job.versionId = coreKit.stringHelpers.uuid_v4();

			job.data = "<data>"+
				"<startDate value=\"" + ow.util.date.toISO8601(5, new Date(Date.now() + 300000)) + "\"/>"+
				"<automator masterId=\"" + macro.masterId + "\" version=\"" + macro.version + "\" type=\"" + macro.automatorType + "\"/>"+
				"<lastExecutionDate value=\"\"/>"+
				"</data>";
				
			//alert(JSON.stringify(macro));
			return [macro, job];

			/*
				 var theMacro = "<outwitAutomator>\n"+
				 "<documentproperties>\n"+
				 "<url>"+ currentOptions["initialURI"] +"</url>\n"+
				 "<masterId>{"+masterId+"}</masterId>\n"+
				 "<name>"+ macroName +"</name>\n"+
				 "<version>1.0</version>\n"+
				 "<versionId>{"+versionId+"}</versionId>\n"+
				 "<kernelVersion>"+ kernelVersion +"</kernelVersion>\n"+
				 "<creationOutfit>Images</creationOutfit>\n"+
				 "<author/>\n"+
				 "<company/>\n"+
				 "<created>"+ creationDate +"</created>\n"+
				 "<lastModified>"+ modificationDate +"</lastModified>\n"+
				 "<comments/>\n"+
				 "<automatorType>macro</automatorType>\n"+
				 "<options>"+preferencesToSet+"</options>\n"+
				 "<hash>##hash##</hash>\n"+
				 "</documentproperties>\n"+
				 "<data>\n"+
				 "<macro>outwit://"+ currentOptions["initialURI"] +"&amp;&amp;"+ MAUOptions +"</macro>\n"+
				 "<destination>\n"+
				 "<resultsFolder></resultsFolder>\n"+
				 "<resultsExist>index</resultsExist>\n"+
				 "<filesFolder>"+ (currentOptions["oWImages.autocatch.autosave.folder"]?currentOptions["oWImages.autocatch.autosave.folder"]:"") +"</filesFolder>\n"+
				 "<filesExist>"+(currentOptions["oWImages.autorename.pattern"]?"index":"overwrite")+"</filesExist>\n"+
				 "<splitData/>\n"+
				 "</destination>\n"+
				 "<detailedProperties>false</detailedProperties>\n"+
				 "</data>\n"+
				 "</outwitAutomator>";
				 */

		}catch(e){
			alert(e);
		}
	}		
};
