/* You may find the license in the LICENSE file */

Components.utils.import('resource://dta/support/timers.jsm');
const Timers = new TimerManager();

var Dialog = {
	downloads: null,
	get isFullyDisabled() {
		return $('directory', 'renaming', 'hash').every(
			function(e) {
				return e.hasAttribute('disabled');
			}
		);
	},
	load: function DTA_load() {
		try {
			// d is an Array of Downloads
			this.downloads = window.arguments[0];
			if (this.downloads.length == 1) {
				let d = this.downloads[0];
				$("infoIcon").src = d.largeIcon;
				$("infoURL").value = d.urlManager.url.spec;
				$("infoDest").value = d.destinationFile;
				$("mirrorsText").value = _("mirrorsText", [d.urlManager.length]);
				document.title = d.destinationName;
			
				if (d.referrer) {
					$('sourcePage')._value = $("sourcePage").value = d.referrer.spec;
				}
				if (!d.isOf(FINISHING | COMPLETE)) {
					$('sourcePage').removeAttribute('readonly');
				}
				
				$('renaming').value = d.mask;
				$('directory').value = d.pathName;
				if (d.hashCollection) {
					$('hash').value = d.hashCollection.full;
				}
				$('description').value = d.description;
				this.item = d;
				Tooltip.init();
				Tooltip.start(d);
			}
			else {
				// more than just one download
				$('infoDest').value = document.title;
				for each (let e in $('infoURL', 'infoSize', 'sourcePage', 'mirrorsText')) {
					e.value = "---";
					e.disabled = true;
				}
				$('mirrorRow').collapsed = true;
				$("hash").setAttribute('readonly', 'true');
				$("hash").setAttribute('disabled', 'true');
	
				let mask = this.downloads[0].mask;
				$('renaming').value = 
					this.downloads.every(function(e, i, a) { return e.mask == mask; })
					? mask
					: '';
	
				let dir = String(this.downloads[0].pathName);
				$('directory').value = 
					this.downloads.every(function(e) { return e.pathName == dir; })
					? dir
					: '';
				$('canvasGrid').hidden = true;
			}				
			if (this.downloads.every(function(d) { return d.isOf(COMPLETE | FINISHING); })) {
				for each (let e in $('directory', 'renaming', 'mask', 'browsedir')) {
					e.setAttribute('readonly', 'true');
					e.setAttribute('disabled', 'true');
				}
			}
			if (this.isFullyDisabled) {
				$('dTaDownloadInfo').buttons = 'accept';
			}			
		}
		catch(ex) {
			Debug.log('load', ex);
		}
		window.setTimeout(function() {
			window.sizeToContent();
			addEventListener("resize", function() Dialog.resize(), true);
		}, 0);
	},
	accept: function DTA_accept() {
		if (this.isFullyDisabled) {
			return true;
		}		
		if (!this.check()) {
			return false;
		}
		
		let win = window.arguments[1];

		let directory = $('directory').value.trim();
		directory = !!directory ? directory.addFinalSlash() : '';
		$('directory').value = directory;
		
		let mask = $('renaming').value.trim();
		mask = mask || '';
		$('renaming').value = mask;
		
		let description = $('description').value;
		description = description.length ? description : '';
		
		let sp = $('sourcePage');
		let newRef = null;
		if (!sp.hasAttribute('readonly') && sp._value != sp.value) {
			newRef = sp.value;
		}
		
		if (this.downloads.length == 1) {
			let d = this.downloads[0];
			if ($('hash').isValid) {
				var h = $('hash').value;
				if (!h) {
					d.hashCollection = null;
				}
				else if (!d.hashCollection || h.sum != d.hashCollection.full.sum || h.type != d.hashCollection.full.type) {
					d.hashCollection = new DTA.HashCollection(h);
					if (h && d.is(COMPLETE)) {
						// have to manually start this guy ;)
						d.verifyHash();
					}
				}
			}
		}
		
		for each (let d in this.downloads) {
			if (!d.isOf(COMPLETE | FINISHING)) {
				if (directory) {
					d.pathName = directory;
				}
				if (mask) {
					d.mask = mask;
				}
			}
			if (description) {
				d.description = description;
			}
			if (newRef) {
				try {
					d.referrer.spec = newRef;
				}
				catch (ex) {
					Debug.log("failed to set referrer to", newRef);
				}
			}
			d.save();
		}
		return true;
	},
	unload: function() {
		Tooltip.stop();
		Timers.killAllTimers();
		return true;
	},
	browseDir: function DTA_browseDir() {
		// let's check and create the directory
		var newDir = Utils.askForDir(
			$('directory').value,
			_("validdestination")
		);
		if (newDir) {
			$('directory').value = newDir;
		}
	},
	manageMirrors: function DTA_manageMirrors() {
		if (this.downloads.length != 1) {
			// only manage single downloads
			return;
		}
		let download = this.downloads[0];
		let mirrors = download.urlManager.toArray();
		openDialog(
			'chrome://dta/content/dta/mirrors.xul',
			null,
			"chrome,dialog,resizable,modal,centerscreen",
			mirrors
		);
		if (mirrors.length) {
			download.replaceMirrors(mirrors);
			Debug.logString("New mirrors set " + mirrors);
			$("mirrorsText").value = _("mirrorsText", [download.urlManager.length]);			
		}		
	},
	check: function DTA_check() {
		var dir = $('directory').value.trim();
		if (!dir.length || !$('renaming').value.trim().length) {
			return false;
		}
		if (!Utils.validateDir(dir)) {
			alert(_(dir.length ? 'alertinvaliddir' : 'alertnodir'));
			var newDir = Utils.askForDir(null, _("validdestination"));
			$('directory').value = newDir ? newDir : '';
			return false;
		}
		if (!$('hash').isValid) {
			alert(_('alerthash'));
			return false;
		}
		return true;
	},
	resize: function() {
		Tooltip.start(this.item);
		return true;
	}
};
addEventListener("load", function() Dialog.load(), true);
addEventListener('unload', function() Dialog.unload(), true);