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

const EXPORTED_SYMBOLS = ['FileExtensionSheet'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const module = Cu.import;
const Exception = Components.Exception;

module("resource://dta/utils.jsm");
module("resource://dta/support/icons.jsm");
module("resource://dta/support/timers.jsm");

const Timers = new TimerManager();

ServiceGetter(this, "Atoms", "@mozilla.org/atom-service;1", "nsIAtomService");

extendString(String);

function FileExtensionSheet(window) {
	this._windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
	
	document = window.document;
	this._stylesheet = null;
	try {
		for each (let ss in document.styleSheets) {
			Debug.log("sheet: " + ss.href);
			if (/^chrome:\/\/dta\//.test(ss.href)) {
				this._stylesheet = ss;
				Debug.log("found stylesheet " + ss.href + ", rules: " + ss.cssRules.length);
				break;
			}
		}
		if (!this._stylesheet) {
			throw new Exception("didn't find stylesheet");
		}
	}
	catch (ex) {
		Debug.log("sheet:", ex);
	}

	this._entries = {};
}

FileExtensionSheet.prototype = {
	getAtom: function FES_getAtom(fileName, metalink) {
		let ext = fileName.getExtension();
		if (!ext) {
			ext = 'unknown';
		}
		if (metalink) {
			ext = 'metalink';
		}
		let key = 'ext:' + ext;
		let entry = this._entries[key];
		if (!entry) {
			entry = Atoms.getAtom("icon" + newUUIDString().replace(/\W/g, ''));
			let rule = 'treechildren::-moz-tree-image(iconic,' 
				+ entry.toString()
				+ ') { list-style-image: url('
				+ getIcon('file.' + ext, metalink || ext == 'metalink')
				+ ') !important; }';
			this._stylesheet.insertRule(rule, this._stylesheet.cssRules.length);
			Debug.log("sheet: " + rule);
			if (!this._timer) {
				// this is a moz-2 hack, as it will otherwise not correctly redraw!
				this._timer = Timers.createOneshot(0, this._updateSheet, this);
			}
			this._entries[key] = entry;
		}
		return entry;
	},
	_updateSheet: function FES__updateSheet() {
		delete this._timer;
		this._windowUtils.redraw();
	}
};